0

我有两个疑问

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

4 回答 4

0

You can UNION them in the following fashion:

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 

Or use UNION ALL if your logic allows it.

于 2013-11-11T23:32:43.837 回答
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
于 2013-11-11T23:27:25.547 回答
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]
于 2013-11-12T04:46:05.013 回答
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
于 2013-11-11T23:41:20.000 回答