2014-10-19 93 views
0

試圖顯示某些日期的銷售。列應該是那些說日期。寫更好的方法來寫這個SQL Server查詢?

得到它的工作,但代碼是如此混亂和複雜,我的直覺告訴我必須有一個簡單的方法來寫這個。

任何人都可以指向正確的方向或想出更優雅的解決方案嗎?

查詢

SELECT 
    (SELECT Jul10.TotalSales 
    FROM 
    (SELECT sale.SaleDate, SUM (sale_bow.Qty * bow.Price) As TotalSales 
    FROM sale 
     INNER JOIN sale_bow ON sale_bow.SaleID = sale.SaleID 
     INNER JOIN bow ON bow.BowID = sale_bow.BowID GROUP BY sale.SaleDate) As Jul10 
    WHERE Jul10.SaleDate ='1999-07-10') AsJul10, 
    (SELECT Jul11.TotalSales 
     FROM (SELECT sale.SaleDate, SUM (sale_bow.Qty * bow.Price) As TotalSales 
     FROM sale 
      INNER JOIN sale_bow ON sale_bow.SaleID = sale.SaleID 
      INNER JOIN bow ON bow.BowID = sale_bow.BowID 
GROUP BY sale.SaleDate) As Jul11 
    WHERE Jul11.SaleDate ='1999-07-11') As Jul11, 
(SELECT Jul12.TotalSales 
    FROM 
(SELECT sale.SaleDate, SUM (sale_bow.Qty * bow. Price) As TotalSales 
    FROM sale 
     INNER JOIN sale_bow ON sale_bow.SaleID = sale.SaleID 
     INNER JOIN bow ON bow.BowID = sale_bow.BowID GROUP BY sale.SaleDate) 
As Jul12 WHERE Jul12.SaleDate = '1999-07-12') 
As Jul12, (SELECT Jul13.TotalSales 
    FROM (SELECT sale.SaleDate, SUM (sale_bow.Qty * bow.Price) As TotalSales 
    FROM sale 
     INNER JOIN sale_bow ON sale_bow.SaleID = sale.SaleID 
     INNER JOIN bow ON bow.BowID = sale_bow.BowID 
GROUP BY sale.SaleDate) As Jul13 WHERE Jul13.SaleDate ='1999-07-13') As Jul13 
+0

也許嘗試codereview.se – codenheim 2014-10-19 22:46:59

回答

2

試試這個:

SELECT 
    Jul10 = SUM(CASE WHEN SaleDate = '1999-07-10' THEN sale_bow.Qty * bow.Price ELSE 0 END), 
    Jul11 = SUM(CASE WHEN SaleDate = '1999-07-11' THEN sale_bow.Qty * bow.Price ELSE 0 END), 
    Jul12 = SUM(CASE WHEN SaleDate = '1999-07-12' THEN sale_bow.Qty * bow.Price ELSE 0 END), 
    Jul13 = SUM(CASE WHEN SaleDate = '1999-07-13' THEN sale_bow.Qty * bow.Price ELSE 0 END) 
FROM 
    sale 
    INNER JOIN sale_bow ON sale_bow.SaleID = sale.SaleID 
    INNER JOIN bow ON bow.BowID = sale_bow.BowID 
相關問題