A few ways to do a SQL

Source: Internet
Author: User

One day in a technology group to see someone sent such a figure for help, a look at the problem is to examine the use of SQL row to column

I thought the first time I think of Oracle's decode function to write, but also think that the topic is not specifically what kind of database ~ If you use decode, under MySQL is completely different usage (also because this time I know that MySQL also has decode method, But unlike Oracle, other databases are not being researched.

So I responded by writing a SQL

The first thought of sql¶

SelectT1.d,t1.c1'win', T2.C2'Negative'  from(Select Count(Result) c1,d fromT_resultwhereResult= 'win' Group  byd) T1 Left outer Join(Select Count(Result) c2,d fromT_resultwhereResult= 'Negative' Group  byd) T2 onT1.d=T2.d

This kind of writing is more intuitive, is to take the "win" out, in taking "negative" out, and finally associated with the date

PS: Here the T_result is the data table, D is the time column, result is the outcome column

I thought about it later, so the result is out, but in fact, the efficiency is not high, because two times select will lead to two of the table scan, because the previous study of Oracle, these are still more sensitive to these, so later rewritten a bit

(May not write the best, but at least more than the initial progress, performance has improved, after all, optimization is a step-by-step)

SELECTDSUM( Case  whenResult='win'  Then 1             ELSE 0             END),         SUM( Case  whenResult='Negative'  Then 1             ELSE 0             END) fromT_resultGROUP  byD

So sweep the surface once and the table will be able to produce results.

Finally, we enclose the decode function of Oralce.

SELECT D,sum(decode (result,' win ',1,0)),sum (Decode (result,' negative ',1,0)) from T_result GROUP  by D

A few ways to do a SQL

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.