How to insert data from 4 queries into one table when the 4 queries have data that are not unique?

前端 未结 4 1665
小蘑菇
小蘑菇 2021-01-17 06:46

to be more clear I have these kind of data.

Query 1) Data from 2016

Item       Price        Quantity

Shoe        20             10
Shoe        30            


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-17 07:11

    Try this as just an idea-

    SELECT Item,
    SUM(Price2016),SUM(Quantity2016),
    SUM(Price2017),SUM(Quantity2017),
    SUM(Price2018),SUM(Quantity2018),
    SUM(Price2019),SUM(Quantity2019)
    FROM
    (
        SELECT Item, 
        Price Price2016, Quantity  Quantity2016,
        NULL Price2017,NULL   Quantity2017  
        NULL Price2018,NULL   Quantity2018   
        NULL Price2019, NULL  Quantity2019
        FROM 2016
    
        UNION ALL
    
        SELECT Item, 
        NULL Price2016, NULL Quantity2016,
        Price Price2017,Quantity Quantity2017  
        NULL Price2018,NULL   Quantity2018   
        NULL Price2019, NULL  Quantity2019
        FROM 2017
    
        UNION ALL
    
        SELECT Item, 
        NULL Price2016, NULL  Quantity2016,
        NULL Price2017,NULL   Quantity2017  
        Price Price2018,Quantity   Quantity2018   
        NULL Price2019, NULL  Quantity2019
        FROM 2018
    
        UNION ALL
    
        SELECT Item, 
        NULL Price2016, NULL Quantity2016,
        NULL Price2017,NULL   Quantity2017  
        NULL Price2018,NULL   Quantity2018   
        Price Price2019, Quantity Quantity2019
        FROM 2019
    )A
    GROUP BY Item
    

提交回复
热议问题