我有一個查詢與CASE
聲明,我需要做一個GROUP BY
的別名。我明白,不能這樣做,所以我試圖使用子查詢,但它不工作。T-SQL 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
被註釋掉需要兩列以某種方式包括在內。有什麼建議麼?
首先,您必須將字段'sd.SBQSHP'和'sd.SBEPRC'添加到您的子選擇。那麼拋出什麼錯誤? – Trinimon 2013-03-26 20:36:51
將字段添加到子選擇後,將列上的別名更改爲「a」以匹配您的子查詢別名。 – 2013-03-26 20:37:59
這樣做了。我不知道爲什麼我沒有想到......謝謝! – tsqln00b 2013-03-26 20:38:38