如何组合两个查询

时间:2013-11-11 23:25:12

标签: sql sql-server tsql sql-server-2008-r2

我有两个问题

1)

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

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

我想要一个结果:

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

我该怎么做?

我试过工会&全联盟

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

有没有办法可以看到我希望看到的格式的结果?

4 个答案:

答案 0 :(得分:0)

由于我不知道他们的关系,我更喜欢使用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

答案 1 :(得分:0)

您可以通过以下方式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

答案 2 :(得分:0)

尝试:

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

答案 3 :(得分:0)

我会使用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]