中分組中的子集值請考慮此場景:在PIVOT
我們有存儲訂單規格的訂單表。其中一個規格是貨幣。我在該表中有幾種貨幣,如美元,歐元,英鎊,日元,迪拉姆,里亞爾,盧比。 美元,歐元,英鎊是主要貨幣。我想在我的查詢中將其他人分組在1組中。我如何使用PIVOT
命令做到這一點?
我想創建這樣這樣的結果:
ProductCategory Dollar Euro Pound Others
---------------------------------------------------------------
P1 1000 2000 500 880
P2 1200 100 200 750
P3 1900 8000 700 640
P4 1500 500 1000 270
P5 2000 1700 1200 1000
感謝
更新1)
我的源表是這樣的:
ProductCategory Currency Amount
----------------------------------------
P1 Dollar 100
P2 Euro 500
P3 Dollar 100
P4 Yen 200
P1 Dollar 100
P3 Rupee 50
...
更新2)
declare @tbl table
(
Product nvarchar(50),
Cur nvarchar(50),
Amount int
)
insert into @tbl values
('p1', 'dollar',100),
('p2', 'euro',100),
('p3', 'pound',100),
('p1', 'a',100),
('p1', 'b',100),
('p2', 'c',100),
('p3', 'dollar',100),
('p3', 'euro',100),
('p2', 'euro',100),
('p2', 'euro',100),
('p1', 'j',100)
SELECT pv.Product
,ISNULL(pv.Dollar,0) AS [Dollar]
,ISNULL(pv.Euro,0) AS [Euro]
,ISNULL(pv.Pound,0) AS [Pound]
,ISNULL(pv.Other,0) AS [Other]
FROM (
SELECT *
,CASE
WHEN [Cur] NOT IN ('dollar','euro','pound') THEN 'Other'
ELSE [Cur]
END AS [newCurrency]
FROM @tbl
)as a
PIVOT (
SUM([Amount])
FOR [newCurrency] IN ([dollar],[euro],[pound],[Other])
)as pv
,並得到這樣的結果:
向我們展示您的源表。 –