簡體   English   中英

如何合並兩個查詢

[英]How to combine two queries

我有兩個疑問

1)

select Year , Month, Sum(Stores) from ABC ;

2) 
select Year, Month , Sum(SalesStores) from DEF ; 

我想要這樣的結果:

 **Year, Month , Sum(Stores), Sum(SalesStores)**

我該怎么做 ?

我嘗試了Union&Union all

select Year , Month, Sum(Stores) from ABC union
select Year, Month , Sum(SalesStores) from DEF ; 

我在輸出中僅看到3列

Year, Month Sum(Stores).

這是表格:

Year, Month Stores

Year Month SalesStores

有什么辦法可以以我想要的格式查看結果?

因為我不知道他們的關系,所以我更喜歡使用UNION ALL

SELECT  Year, 
        Month, 
        MAX(TotalStores) TotalStores, 
        MAX(TotalSalesStores) TotalSalesStores
FROM
        (
            SELECT  Year, Month, 
                    SUM(Stores) TotalStores, 
                    NULL TotalSalesStores 
            FROM    ABC
            UNION ALL
            SELECT  Year, Month, 
                    NULL TotalStores, 
                    SUM(SalesStores) TotalSalesStores 
            from    DEF 
        ) a
GROUP   BY Year, Month

您可以按以下方式UNION它們:

SELECT Year , Month, Sum(Stores)  As Stores, NULL As SalesStores from ABC 

UNION

SELECT Year , Month,  NULL As Stores, Sum(Stores) As SalesStores from ABC 

或在邏輯允許的情況下使用UNION ALL

嘗試:

SELECT Year, Month, SUM(TotalStores) as TotalAllStores, SUM(TotalSalesStore) as TotalAllSalesStore
FROM
(
 SELECT Year , Month, Sum(Stores) as TotalStores, 0 as TotalSalesStore from ABC union
 UNION ALL
 SELECT Year, Month , 0 as TotalStores, Sum(SalesStores) as TotalSalesStore from DEF 
) SalesByYearMonth
GROUP BY Year, Month

我將這樣使用FULL OUTER JOIN

SELECT ISNULL(x.[Year], y.[Year]) AS [Year],
ISNULL(x.[Month], y.[Month]) AS [Month],
x.Sum_Stores,
y.Sum_SalesStores
FROM (select Year , Month, Sum(Stores) AS Sum_Stores from ABC ...) AS x
FULL OUTER JOIN (select Year, Month , Sum(SalesStores) AS Sum_SalesStores from DEF ...) AS y
ON x.[Year] = y.[Year] AND x.[Month] = y.[Month]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM