2013-03-26 46 views
0

我有一個查詢與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 

被註釋掉需要兩列以某種方式包括在內。有什麼建議麼?

+0

首先,您必須將字段'sd.SBQSHP'和'sd.SBEPRC'添加到您的子選擇。那麼拋出什麼錯誤? – Trinimon 2013-03-26 20:36:51

+0

將字段添加到子選擇後,將列上的別名更改爲「a」以匹配您的子查詢別名。 – 2013-03-26 20:37:59

+0

這樣做了。我不知道爲什麼我沒有想到......謝謝! – tsqln00b 2013-03-26 20:38:38

回答

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; 
0

只需選擇你需要在你的子查詢彙總與別名值「一」

添加到子查詢 「一」 select語句:

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

在頂級SELECT語句取消註釋SUM聲明,但變化的別名從 「SD」 到 「一」

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