请考虑这种情况:
我们有订单表来存储订单规格。其中一个规格是货币。我在该表中有几种货币,如 Dollar,Euro,Pound,Yen,Dirham,Rial,Rupee 。 美元,欧元,英镑是主要货币。我想在我的查询中将其他人归为一组。我如何使用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
得到这个结果:
答案 0 :(得分:1)
尝试此查询
SELECT pv.ProductCategory
,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 [Currency] NOT IN ('Dollar','Euro','Pound') THEN 'Other'
ELSE [Currency]
END AS [newCurrency]
FROM #tmp
)as a
PIVOT (
MAX([Amount])
FOR [newCurrency] IN ([Dollar],[Euro],[Pound],[Other])
)as pv
答案 1 :(得分:1)
你快到了。在Update 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
,sum(ISNULL(pv.Dollar,0)) AS [Dollar]
,sum(ISNULL(pv.Euro,0)) AS [Euro]
,sum(ISNULL(pv.Pound,0)) AS [Pound]
,sum(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
group by product
答案 2 :(得分:-1)
尝试此查询,您可以根据产品汇总其他货币。
select productCategory,
sum(dollar),
sum(euro),
sum(pound),
sum(others)
from order
group by productCategory
希望它会有所帮助。