optimization of one SQL statement (SQL Server)

Source: Internet
Author: User

The earliest notation:

 withT as(SELECT  Case  whenCol1 is NULL ORCol1=N"'  ThenCol2ElseCol1End  asCode, Case  whenCol1 is NULL ORCol1=N"'  Then 1 Else 0 End  asFlag fromYMWHEREcol_076between '2018-07-25'  and '2018-08-03'  andcol_478=N'xx'  andcol_346 likeN'%dd%'), D as(SELECTCode,province,city fromAdds)SELECTProvince asProvince, City asCityCOUNT(1) Number of votes from (SELECTa.dr_250 asprovince,a.dr_251 asCity fromTINNER JOINTB asA ona.dr_203=T.codeWHERET.flag=0 UNION  All SELECTD.province,d.city fromTINNER JOIND onD.code=T.codeWHERET.flag=1 UNION  All SELECT "'  asProvince,"'  asCity fromTWHERECode is NULL ORCode=N"') asSGROUP  byprovince,city;

The latest wording:

SELECT  Case  whenCol1 is NULL ORCol1=N"'  ThenCol2ElseCol1End  asCode, Case  whenCol1 is NULL ORCol1=N"'  Then 1 Else 0 End  asFlag into#T fromYMWHEREcol_076between '2018-07-25'  and '2018-08-03'  andcol_478=N'xx'  andcol_346 likeN'%dd%';SELECTCode,province,city into#D fromAdds;SELECTProvince asProvince, City asCityCOUNT(1) Number of votes from (SELECTa.dr_250 asprovince,a.dr_251 asCity from#TINNER JOINTB asA ona.dr_203=#T. CodeWHERE#T. Flag=0UNION  AllSELECT#D. Province, #D. City from#TINNER JOIN#D on#D. Code=#T. CodeWHERE#T. Flag=1UNION  AllSELECT "'  asProvince,"'  asCity from#TWHERECode is NULL ORCode=N"') asSGROUP  byprovince,city;DROP Table#T;DROP Table#D;

The new wording is much higher than the original writing performance (the original statement execution time out), the biggest reason is the understanding of the WITH statement is wrong!!!

optimization of one SQL statement (SQL Server)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.