【发布时间】:2015-03-21 04:42:23
【问题描述】:
我有一个名为Product的表:
create table product (
ProductNumber varchar(10),
ProductName varchar(10),
SalesQuantity int,
Salescountry varchar(10)
);
示例值:
insert into product values
('P1', 'PenDrive', 50, 'US')
, ('P2', 'Mouse', 100, 'UK')
, ('P3', 'KeyBoard', 250, 'US')
, ('P1', 'PenDrive', 300, 'US')
, ('P2', 'Mouse', 450, 'UK')
, ('P5', 'Dvd', 50, 'UAE');
我想动态生成Salescountry's 名称并显示该国家/地区的SalesQuantity 销售总和。
预期结果:
ProductName US UK UAE
----------------------------
PenDrive 350 0 0
Mouse 0 550 0
KeyBoard 250 0 0
Dvd 0 0 50
我是使用 SQL Server 2008 R2 完成的:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(SalesCountry)
FROM Product
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT ProductName, ' + @cols + ' from
(
select ProductName
, SalesQuantity as q
, Salescountry
from Product
) x
pivot
(
SUM(q)
for Salescountry in (' + @cols + ')
) p '
PRINT(@query);
execute(@query);
如何在 Postgres 中实现这一点?
【问题讨论】:
-
@Winged Panther,
Case不是动态查询的好建议。 -
@Winged Panther,这就是我在这里面临的问题。在 SQL Server 中,我使用
Stuff。 -
@WingedPanther,是的!我也提到过。但是有一个
column list。但在这里我希望它应该是动态的(SalesCountry)。 -
检查this
-
@PuskerGyörgy:警告一句:链接博客中的代码没有转义标识符,这会破坏非标准名称并允许 SQL 注入。
标签: postgresql pivot crosstab postgresql-9.3