6
我有三個表:
產品SQL查詢像輸出在SQL Server查詢相關的表生成矩陣
ProductID ProductName
1 Cycle
2 Scooter
3 Car
客戶
CustomerID CustomerName
101 Ronald
102 Michelle
103 Armstrong
104 Schmidt
105 Peterson
交易
TID ProductID CustomerID TranDate Amount
10001 1 101 01-Jan-11 25000.00
10002 2 101 02-Jan-11 98547.52
10003 1 102 03-Feb-11 15000.00
10004 3 102 07-Jan-11 36571.85
10005 2 105 09-Feb-11 82658.23
10006 2 104 10-Feb-11 54000.25
10007 3 103 20-Feb-11 80115.50
10008 3 104 22-Feb-11 45000.65
我已經寫了一個查詢組的交易是這樣的:
SELECT P.ProductName AS Product,
C.CustName AS Customer,
SUM(T.Amount) AS Amount
FROM Transactions AS T
INNER JOIN Product AS P
ON T.ProductID = P.ProductID
INNER JOIN Customer AS C
ON T.CustomerID = C.CustomerID
WHERE T.TranDate BETWEEN '2011-01-01' AND '2011-03-31'
GROUP BY
P.ProductName,
C.CustName
ORDER BY
P.ProductName
其給出結果是這樣的:
Product Customer Amount
Car Armstrong 80115.50
Car Michelle 36571.85
Car Schmidt 45000.65
Cycle Michelle 15000.00
Cycle Ronald 25000.00
Scooter Peterson 82658.23
Scooter Ronald 98547.52
Scooter Schmidt 54000.25
我需要查詢的結果以矩陣形式是這樣的:
Customer |------------ Amounts ---------------
Name |Car Cycle Scooter Totals
Armstrong 80115.50 0.00 0.00 80115.50
Michelle 36571.85 15000.00 0.00 51571.85
Ronald 0.00 25000.00 98547.52 123547.52
Peterson 0.00 0.00 82658.23 82658.23
Schmidt 45000.65 0.00 54000.25 99000.90
請幫我達到上面的r在SQL Server 2005.中使用多重視圖甚至是時間表對我來說都很好。
非常感謝您的解決方案。我的產品列表不是靜態的(用戶可以添加產品)。隨着產品的增長,必須創建許多列。數據也是動態的。請修改查詢,以便我可以查詢動態數據。 – Nagesh 2011-03-07 09:20:47
@Nagesh,你可以在我們自己的SO本身找到不同的動態轉軸實現。看看http://stackoverflow.com/questions/213702/sql-server-2005-pivot-on-unknown-number-of-columns – 2011-03-07 09:25:40
是否有可能實現這一點使用MySQL – arvindwill 2017-12-27 11:34:59