在SQL查询中对多个选择进行分组

时间:2014-05-12 14:33:47

标签: sql sql-server sql-server-2008

我有一个供应商,有两列,TotalStock和Date。我正在尝试编写一个查询,以便按周/月/年为我提供库存总数供应商列表。

所以结果看起来像这样..

SUPPLIER  WEEK MONTH YEAR
SupplierA 50   100   2000
SupplierB 60   150   2500
SupplierC 15   25    200

到目前为止,我一直在玩多种选择,但我无法得到更多:

SELECT Supplier,
    (
    SELECT      Sum(TotalStock)
    FROM        StockBreakdown
    WHERE       Date >= '2014-5-12'
    GROUP BY    Supplier
    ) AS StockThisWeek,
    (
    SELECT      Sum(TotalStock)
    FROM        StockBreakdown
    WHERE       Date >= '2014-5-1'
    GROUP BY    Supplier
    ) AS StockThisMonth,
    (
    SELECT      Sum(TotalStock)
    FROM        StockBreakdown
    WHERE       Date >= '2014-1-1'
    GROUP BY    Supplier
    ) AS StockThisYear

此查询会在每个单独的分组返回多个结果时抛出错误。我觉得我接近解决方案,但无法解决问题

2 个答案:

答案 0 :(得分:2)

您不必使用子查询来实现您想要的目标:

SELECT Supplier
     , SUM(CASE WHEN Date >= CAST('2014-05-12' as DATE) THEN TotalStock END) AS StockThisWeek
     , SUM(CASE WHEN Date >= CAST('2014-05-01' as DATE) THEN TotalStock END) AS StockThisMonth
     , SUM(CASE WHEN Date >= CAST('2014-01-01' as DATE) THEN TotalStock END) AS StockThisYear
FROM  StockBreakdown
GROUP BY Supplier

答案 1 :(得分:1)

您可能需要使列的选择仅返回单个结果。你可以尝试这个(目前未测试):

SELECT Supplier,
(
    SELECT TOP 1 StockThisWeek FROM
    (
       SELECT      Supplier, Sum(TotalStock) AS StockThisWeek
       FROM        StockBreakdown
       WHERE       Date >= '2014-5-12'
       GROUP BY    Supplier
    ) tmp1
    WHERE tmp1.Supplier = Supplier 
) AS StockThisWeek,

(
    SELECT TOP 1 StockThisMonth FROM
    (
       SELECT      Supplier, Sum(TotalStock) AS StockThisMonth
       FROM        StockBreakdown
       WHERE       Date >= '2014-5-1'
       GROUP BY    Supplier
    ) tmp2
    WHERE tmp2.Supplier = Supplier 
) AS StockThisMonth, 

...

这将选择供应商,然后通过从之前创建的选择中选择第一个条目,尝试创建两列StockThisWeekStockThisMonth。通过GROUP BY,每个供应商应该只有一个条目,因此您不会丢失和数据。