如何使用查询组合来自不同表的数据

时间:2013-12-17 16:31:48

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

我有一组表格,如下所示。

你能让我知道如何实现所需的输出吗?

CREATE TABLE #ABC([Year] INT, [Month] INT,Customer Varchar(10), SalesofProductA INT);
CREATE TABLE #DEF([Year] INT, [Month] INT,Customer Varchar(10), SalesofProductB INT);
CREATE TABLE #GHI([Year] INT, [Month] INT,Customer Varchar(10), SalesofProductC INT);

INSERT #ABC VALUES (2013,1,'PPP',1);
INSERT #ABC VALUES (2013,1,'QQQ',2);
INSERT #ABC VALUES (2013,2,'PPP',3);

INSERT #DEF VALUES (2013,1,'QQQ',4);
INSERT #DEF VALUES (2013,1,'RRR',5);
INSERT #DEF VALUES (2013,2,'PPP',6);

INSERT #GHI VALUES (2013,1,'QQQ',7);
INSERT #GHI VALUES (2013,2,'RRR',8);
INSERT #GHI VALUES (2013,3,'PPP',9);
   INSERT #GHI VALUES (2013,3,'QQQ',10);

我的查询目前看起来像这样。 @Month和@Year作为参数提供

SELECT
    -- select the sum for each year/month combination using a correlated subquery (each result from the main query causes another data retrieval operation to be run)
    (SELECT SUM(SalesofProductA) FROM #ABC WHERE [Year]=T.[Year] AND [Month]=T.[Month]) AS [Sum_SalesofProductA]
    ,(SELECT SUM(SalesofProductB) FROM #DEF WHERE [Year]=T.[Year] AND [Month]=T.[Month]) AS [Sum_SalesofProductB]
    ,(SELECT SUM(SalesofProductC) FROM #GHI WHERE [Year]=T.[Year] AND [Month]=T.[Month]) AS [Sum_SalesofProductC]
FROM (
    -- this selects a list of all possible dates.
    SELECT [Year],[Month] FROM #ABC
    where Year = @Year and Month = @Month
    UNION
    SELECT [Year],[Month] FROM #DEF
    where Year = @Year and Month = @Month
     UNION
    SELECT [Year],[Month] FROM #GHI
    where Year = @Year and Month = @Month
) AS T;

现在我看到这样的输出:对于@Month和@Year的特定值

 SalesofProductA, SalesofProductB, SalesofProductC 

我希望看到的是:

[Customer],SalesofProductA, SalesofProductB, SalesofProductC 

有谁知道怎么做?

1 个答案:

答案 0 :(得分:0)

SELECT Customer 
          , SUM(COALESCE(P.[ProductA], 0)) AS [ProductA] 
          , SUM(COALESCE(P.[ProductB], 0)) AS [ProductB] 
          , SUM(COALESCE(P.[ProductC], 0)) AS [ProductC] 
FROM
(
SELECT Customer , SUM(SalesofProductA) AS  Sales, 'ProductA' AS ProductName 
FROM #ABC 
GROUP BY Customer
UNION ALL 
SELECT Customer , SUM(SalesofProductB) AS  Sales, 'ProductB' AS ProductName 
FROM #DEF 
GROUP BY Customer
UNION ALL 
SELECT Customer , SUM(SalesofProductC) AS  Sales, 'ProductC' AS ProductName 
FROM #GHI 
GROUP BY Customer
) Q
   PIVOT ( SUM(Sales) 
           FOR ProductName
           IN ([ProductA], [ProductB], [ProductC])
           )P
GROUP BY  Customer

<强>结果

Customer    ProductA    ProductB    ProductC
PPP             4          6           9
QQQ             2          4           17
RRR             0          5           8