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

前端 未结 4 1546
小蘑菇
小蘑菇 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:13

    Try use it, It includes GROUP BY the items and the prices.

    SELECT Item,
    Price,
    SUM(Quantity2016),
    SUM(Quantity2017),
    ...
    FROM
    (
        --query 1:
    
        SELECT Item, 
        Price,
        Quantity AS Quantity2016,
        NULL AS Quantity2017  
        NULL AS Quantity2018   
        NULL AS Quantity2019
        FROM 2016
    
        UNION ALL
    
        --query 2:
    
        SELECT Item, 
        Price,
        NULL AS Quantity2016,
        Quantity AS Quantity2017  
        NULL AS Quantity2018   
        NULL AS Quantity2019
        FROM 2017
    
        UNION ALL
    
        --query 3:
    
        SELECT Item, 
        Price,
        NULL AS Quantity2016,
        NULL AS Quantity2017  
        Quantity AS Quantity2018   
        NULL AS Quantity2019
        FROM 2018
    
        UNION ALL
        ...
    
    )A
    GROUP BY Item, Price
    

提交回复
热议问题