将多个查询组合在不同的子句中

时间:2012-04-23 02:06:44

标签: sql

我有2个查询,我想合并为一个。基本上我希望2个查询在一个输出表中...输出看起来像这样......

 
Store        GC Sold             Total Cars

1               22                    75

2                24                    88

3                15                    89

问题是我无法弄清楚如何在同一张桌子上找到它。

以下是我的疑问......

SELECT        Store_Number, COUNT_BIG(Quantity_Sold) AS GC Sold
FROM            Invoice_Detail_Tb
WHERE        (Invoice_Date BETWEEN CONVERT(DATETIME, @startdate, 102) AND CONVERT(DATETIME, @enddate, 102)) AND (JLI_Category_Code = 'gc') 
                         AND (Invoice_Detail_Code LIKE 'jlgc%') AND (Invoice_Detail_Type = 'Item')
GROUP BY Store_Number

此输出为:

Store Number      GC Sold

1                    12

2                    13

3                    14
SELECT   Store_Number,
         SUM(Vehicle_Count) AS [Total_Cars]
FROM     Daily_Sales_Tb
WHERE    (Operations_Day BETWEEN CONVERT (DATETIME, @startdate, 102) AND CONVERT (DATETIME, @enddate, 102))
GROUP BY Store_Number;

输出:

Store Number       Total Cars

1                      7

2                      8

3                      9

另外,查询按设计工作。但是,如果我尝试将它们组合起来,则它们是2种不同的聚合函数,因此它不起作用。

1 个答案:

答案 0 :(得分:4)

SELECT A.Store_Number,A.GC_Sold,B.Total_Cars
FROM
(
SELECT        Store_Number, COUNT_BIG(Quantity_Sold) AS GC_Sold
FROM            Invoice_Detail_Tb
WHERE        (Invoice_Date BETWEEN CONVERT(DATETIME, @startdate, 102) AND CONVERT(DATETIME, @enddate, 102)) AND (JLI_Category_Code = 'gc') 
                         AND (Invoice_Detail_Code LIKE 'jlgc%') AND (Invoice_Detail_Type = 'Item')
GROUP BY Store_Number
) A,
(
SELECT   Store_Number,
         SUM(Vehicle_Count) AS [Total_Cars]
FROM     Daily_Sales_Tb
WHERE    (Operations_Day BETWEEN CONVERT (DATETIME, @startdate, 102) AND CONVERT (DATETIME, @enddate, 102))
GROUP BY Store_Number
) B
WHERE A.Store_Number=B.Store_Number;