2015-05-07 60 views
0

我有這個疑問SQL服務器的動態情況當

SELECT 
    Product, Description, 
    Sum(CASE WHEN Datum = ’01.2011’ THEN [A_Sales] END) AS [A_salesFeb], 
    Sum(CASE WHEN Datum = ’05.2011’ THEN [A_Sales] END) AS [A_salesMay], 
    Sum(CASE WHEN Datum = ’01.2011’ THEN [B_Sales] END) AS [B_salesFeb], 
    Sum(CASE WHEN Datum = ’05.2011’ THEN [B_Sales] END) AS [B_salesMay], 
FROM tblSales 
GROUP BY Product, Description 

現在我需要讓動態的水平基準=「」,工作正常。現在說我現在有08.2012和04.2013 它應該通過並進行匹配。 因此,我將其更改爲以下查詢,但它不起作用。我得到錯誤的數字

SELECT 
    Product, Description, 
    Sum(CASE WHEN Datum = Datum THEN [A_Sales] END) AS [A_salesFeb], 
    Sum(CASE WHEN Datum = Datum THEN [A_Sales] END) AS [A_salesMay], 
    Sum(CASE WHEN Datum = Datum THEN [B_Sales] END) AS [B_salesFeb], 
    Sum(CASE WHEN Datum = Datum THEN [B_Sales] END) AS [B_salesMay], 
FROM tblSales 
GROUP BY Product, Description 

數據採集:我有12桌,我希望用戶能夠選擇任意兩個表動態/或者,然後做一個comparisim。我現在擁有的是靜態的。事情是這樣的: Sample data

+1

添加一些樣本數據,並告訴我們更多的不是「它不工作」。 –

+0

如果您可以提供一些具有所需輸出的樣本數據,這將是可以解決的。 – Tanner

+0

編輯問題 – James

回答

0

基於該數據,並在您的示例數據所需的結果集 - 這是查詢我會寫:

select Datum, Product, sum(FebSales13.A_sales) as A_SalesFeb, 
sum(FebSales13.B_sales) as B_SalesFeb, sum(MaySales12.A_sales) as A_SalesMay, 
sum(MaySales12.B_sales) as B_SalesMay 
from 
    (select Datum, Product, A_sales, B_sales 
    from FebSales13) FebSales13 
inner join 
    (select Datum, Product, A_sales, B_sales 
    from MaySales13) MaySales13 
on FebSales13.Datum = MaySales12.Datum 
and FebSales13.Product = MaySales12.Product 
group by Datum, Product