由于CASE,行没有正确组合?

时间:2015-05-07 21:07:15

标签: sql sql-server sql-server-2012

我正在尝试为多个产品组找到TotalSales的总和,但有些组中包含多个产品组。我认为CASE会起作用,但我的输出并没有正确地组合TotalSales。

我在这里错过了什么概念?我需要做些什么来解决它?

QUERY:

SELECT
    SA3.SalesRepID,
    CASE SA3.ProductGroup1ID
        WHEN  3 THEN  3
        WHEN  8 THEN  8
        WHEN 14 THEN 14
        WHEN 20 THEN 14
        WHEN  5 THEN 14
        WHEN  9 THEN  9
        WHEN 10 THEN  9
        WHEN 11 THEN  9
        WHEN 16 THEN 16
        WHEN 17 THEN 17
        WHEN 19 THEN 19
        ELSE 1 END AS [ProductGroupID],
    SA3.BranchID,
    MONTH(SA3.DocumentDate) [Month],
    YEAR(SA3.DocumentDate) [Year],
    SUM(TotalSales)

FROM SalesAnalysis3 SA3
LEFT JOIN SalesRep SR ON SR.SalesRepID = SA3.SalesRepID

WHERE SR.UserID = 17

GROUP BY SA3.SalesRepID,[ProductGroup1ID],
   SA3.BranchID, MONTH(SA3.DocumentDate), YEAR(SA3.DocumentDate)

ORDER BY
CASE WHEN MONTH(SA3.DocumentDate) < 3 THEN MONTH(SA3.DocumentDate) +12
ELSE MONTH(SA3.DocumentDate) END, YEAR(SA3.DocumentDate), SA3.BranchID, [ProductGroupID]

示例输出:

    SalesRepID  ProductGroupID  BranchID    Month   Year    TotalSales
    17          1               3           3       2014    900.60
    17          1               3           3       2014    1307.24
    17          1               3           3       2014    1735.15
    17          1               3           3       2014    402.65
    17          3               3           3       2014    760.00
    17          8               3           3       2014    28783.14

2 个答案:

答案 0 :(得分:3)

您需要编辑您的组以使用您的案例陈述。现在,您在select中编辑产品ID,但仍在原始产品ID上进行分组。

替换:

GROUP BY SA3.SalesRepID,[ProductGroup1ID],
  SA3.BranchID, MONTH(SA3.DocumentDate), YEAR(SA3.DocumentDate)

使用:

GROUP BY SA3.SalesRepID
,   SA3.BranchID, MONTH(SA3.DocumentDate), YEAR(SA3.DocumentDate),
CASE SA3.ProductGroup1ID
    WHEN  3 THEN  3
    WHEN  8 THEN  8
    WHEN 14 THEN 14
    WHEN 20 THEN 14
    WHEN  5 THEN 14
    WHEN  9 THEN  9
    WHEN 10 THEN  9
    WHEN 11 THEN  9
    WHEN 16 THEN 16
    WHEN 17 THEN 17
    WHEN 19 THEN 19
    ELSE 1 END 

答案 1 :(得分:0)

我同意araphael的回答,但我认为你应该简化case陈述:

(CASE WHEN SA3.ProductGroup1ID in (14, 20, 5) THEN 14
      WHEN SA3.ProductGroup1ID in (9, 10, 11) THEN 9
      WHEN SA3.ProductGroup1ID in (3, 8, 16, 17, 19) THEN SA3.ProductGroup1ID
      ELSE 1
 END) AS [ProductGroupID]