T-SQL GROUP BY ISSUE with CASE STATEMENT

时间:2013-03-26 20:32:38

标签: sql-server tsql

我有一个CASE语句的查询,我需要在别名上执行GROUP BY。我明白不能这样做所以我试图使用子查询,但它不起作用。

以下是我正在处理的查询:

SELECT
    a.Vendor,
    a.Month_Sold
    --SUM(sd.SBQSHP) AS Sales_Qty,
    --SUM(sd.SBEPRC) AS Sales_Dlr
FROM
(SELECT
    sd.IFPRVN AS Vendor,
    vn.ACNAME AS Vendor_Name,
    CASE
        WHEN sd.SBINDT BETWEEN '2012-07-30' AND '2012-08-26' THEN 'August 2012'
        WHEN sd.SBINDT BETWEEN '2012-08-27' AND '2012-09-30' THEN 'September 2012'
        WHEN sd.SBINDT BETWEEN '2012-10-01' AND '2012-10-28' THEN 'October 2012'
        WHEN sd.SBINDT BETWEEN '2012-10-29' AND '2012-11-25' THEN 'November 2012'
        WHEN sd.SBINDT BETWEEN '2012-11-26' AND '2012-12-31' THEN 'December 2012'
        WHEN sd.SBINDT BETWEEN '2013-01-01' AND '2013-01-27' THEN 'January 2013'
        WHEN sd.SBINDT BETWEEN '2013-01-28' AND '2013-02-24' THEN 'Febuary 2013'
        WHEN sd.SBINDT BETWEEN '2013-02-25' AND '2013-03-31' THEN 'March 2013'
    END AS Month_Sold
FROM
    dbo.SalesData sd
    INNER JOIN dbo.S2K_VEND vn ON vn.ACVEND = sd.IFPRVN
WHERE
    sd.SBINDT > '2012-07-29'
AND
    sd.SBCLS IN ('1500')
AND
    sd.SBDIV NOT IN ('4000')
)a
GROUP BY
    a.Vendor,
    a.Month_Sold
ORDER BY
    a.Vendor,
    a.Month_Sold

注释掉的两列需要以某种方式包含在内。有什么建议吗?

2 个答案:

答案 0 :(得分:1)

实际上,在日期输出上添加漂亮的标签应该是表示层的工作。 C#等中的FORMAT()非常强大。除此之外,在最后一个可能的点之前不要转换为漂亮的字符串标签,这将需要多一层:

SELECT 
  Vendor, 
  DATENAME(MONTH, Month_Sold) + ' ' + RTRIM(YEAR(Month_Sold)),
  Sales_Qty,
  Sales_Dlr
FROM
(
  SELECT
    Vendor,
    Month_Sold,
    SUM(SBQSHP) AS Sales_Qty,
    SUM(SBEPRC) AS Sales_Dlr
  FROM
  (
    SELECT
      sd.IFPRVN AS Vendor,
      vn.ACNAME AS Vendor_Name, -- why is this here?
      CASE
        WHEN sd.SBINDT BETWEEN '2012-07-30' AND '2012-08-26' THEN '2012-08-01'
        WHEN sd.SBINDT BETWEEN '2012-08-27' AND '2012-09-30' THEN '2012-09-01'
        ...
        WHEN sd.SBINDT BETWEEN '2013-01-28' AND '2013-02-24' THEN '2013-02-01'
        WHEN sd.SBINDT BETWEEN '2013-02-25' AND '2013-03-31' THEN '2013-03-01'
      END AS Month_Sold
    FROM dbo.SalesData sd
      INNER JOIN dbo.S2K_VEND vn 
      ON vn.ACVEND = sd.IFPRVN
    WHERE sd.SBINDT > '2012-07-29'
    AND sd.SBCLS IN ('1500')
    AND sd.SBDIV NOT IN ('4000')
  ) AS a
  GROUP BY Vendor, Month_Sold
) AS b
ORDER BY
    Vendor,
    Month_Sold;

答案 1 :(得分:0)

只需选择需要在子查询中使用别名“a”

进行聚合的值

添加到子查询“a”选择语句:

SELECT    
    sd.IFPRVN AS Vendor,
    vn.ACNAME AS Vendor_Name,
    sd.SBQSHP,
    sd.SBEPRC
    CASE
        ...

在顶级选择语句中取消注释SUM语句,但将别名从“sd”更改为“a”

SUM(a.SBQSHP) AS Sales_Qty,
SUM(a.SBEPRC) AS Sales_Dlr