如何使用SQL组合Group By Clause中的行

时间:2017-08-28 02:54:31

标签: sql group-by

我有一些SQL需要它根据四个变量(supplier_code,building_code,part_name,part_no)来计算数量。问题出在select语句中我需要使用CASE语句来选择一个建筑,具体取决于transfer_date。但是通过这样做,我现在必须使用Group By中的transfer_date然后生成三个不同的行....我需要将这些行组合起来。

例如 -

enter image description here

应该合并纳皮尔的三个值,但不是因为我必须在组中使用transfer_date。

enter image description here

如何在以下SQL中解决此问题。请记住,这是UPDATE的一部分,因此使用CTE不起作用。

SELECT
    Part_Name,
    Part_No,
    Supplier_Code,
    CASE WHEN Transfer_Date > @EndDate THEN Transfer_Building ELSE Building_Code END AS 'Building_Code',
    SUM(Quantity) AS 'Incoming_Quantity'
FROM Inventory
WHERE
    Regrade = 0 AND
    (CASE WHEN Transfer_Date <= @EndDate THEN Transfer_Date ELSE Add_Date END <= @EndDate) AND
    (Add_Date >= @StartDate OR Transfer_Date >= @StartDate) AND
    Supplier_Code = 'TPP HAMSTEAD' AND Part_No = 'L32730'
GROUP BY
    Transfer_Date,
    Supplier_Code,
    Building_Code,
    Transfer_Building,
    Part_Name,
    Part_No

我可以使用临时表,但想知道是否有更简单的方法来实现这一目标?

1 个答案:

答案 0 :(得分:0)

这是一个T-SQL解决方案(SQL Server)

SELECT
    Part_Name,
    Part_No,
    Supplier_Code,
    CASE 
    WHEN Transfer_Date > @EndDate 
    THEN Transfer_Building 
    ELSE Building_Code END AS 'Building_Code',
    SUM(Quantity) AS 'Incoming_Quantity'
FROM Inventory
WHERE
    Regrade = 0 AND
    (CASE WHEN Transfer_Date <= @EndDate THEN Transfer_Date 
     ELSE Add_Date END <= @EndDate) 
     AND
    (Add_Date >= @StartDate OR Transfer_Date >= @StartDate) 
    AND Supplier_Code = 'TPP HAMSTEAD' 
    AND Part_No = 'L32730'
GROUP BY
    Supplier_Code,
    Part_Name,
    Part_No,
    CASE 
    WHEN Transfer_Date > @EndDate 
    THEN Transfer_Building 
    ELSE Building_Code END