SQL Merge Query Results

Source: Internet
Author: User

When using the JS reporting tool, it is often necessary to provide JSON data for display,

In the SQL query, we need to construct the appropriate query results;

It is used to merge table data with two unrelated relationships.

SELECT    SUM (A1.amount) as amount,    a1.date    from    ((SELECT    SUM (amount) as Amount,    date_format (Time,' %y-%m-%d ') as date        GROUP by    date UNIONAll-SUM (b.value) as S2,    date _format (B.time,'%y-%m-%d ') as D2    from    b    Group by D2)) as A1    GROUP by A1.date
A form of collection, b payment, calculation of daily income (collection-payment)
Calculates the amount in two tables, grouped by date (days)
Note the Time field name, the field in the same position of table A will overwrite the B table field name, so using union requires that the two tables have the same fields
Finally, the results are grouped according to the combined time, and the profit is calculated (poor calculation)
Use union or UNION ALL
such as SELECT * from a UNION ALL SELECT * from B vertical rows merge two tables of data
Display formats such as:
A date

-204 2015-07-06
220 2015-07-15
-60 2015-07-16
220 2015-07-17

In another case, a different alias (shown in a different column) is given to the value given by the condition.

Select    a.date,    sum (A.C1) as S1,    sum (A.C2) as S2 from    (    SELECT    '%y-%m-%d ') as Date,    ifnull (case    B.sta    0 Then COUNT (*) END), 0    ) as C1,    ifnull (case    B.sta     1 Then COUNT (*) END), 0    ) as C2    from  b    Group by B.sta,date    ) as a    group by A.date
According to type sta=0/=1, time grouping, statistic number

The resulting data format:

Date S1 s2

2015-07-06 4 1
2015-07-08 0 1
2015-07-15 0 1
2015-07-16 1 3

SQL Merge Query Results

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.