我选择如下:
SELECT SUBSTRING(Col1, 1, 3) AS 'Series',
b.Col2,
CAST(c.Price * c.Qty AS MONEY) AS Total
FROM tableName a
inner join ....
...
WHERE DATE BETWEEN '1/1/2012' AND '1/31/2012'
AND B IN ( 'C50', 'C51', 'C52', 'C53', 'C54' )
GROUP BY Col1,
b.Col2,
c.Price,
c.Qty
返回此结果集:
Series Col2 Total
---------- ---------- ----------
105 C50 5.00
105 C50 15.00
105 C53 20.00
105 C53 20.00
105 C53 20.00
这就是我希望它的工作方式:
Series C50 C53
---------- ---------- ----------
105 20.00 60.00
不确定如何进行内部选择以获得该结果。有什么想法吗?
答案 0 :(得分:1)
请尝试以下代码。你必须使用PIVOT查询。
create table TableName (Series varchar(20),col2 varchar(10), price decimal(8,2))
insert into TableName values ('105','C50',30)
insert into TableName values ('105','C50',10)
insert into TableName values ('105','C53',20)
insert into TableName values ('105','C53',30)
SELECT Series,
[C50],
[C53]
FROM (SELECT Series,
col2,
price
FROM TableName) AS SourceTable
PIVOT ( SUM(price) FOR col2 IN ([C50],
[C53])
) AS PivotTable;
答案 1 :(得分:0)
对于col2的潜在空值,请尝试以下代码。
注意:您可能需要调整@PIV_COL大小,具体取决于col2的不同记录数。我使用'NO_VAL'作为col2的潜在NULL值。
insert into TableName values ('105',NULL,100)
DECLARE @PIV_COL VARCHAR(100)
SELECT @PIV_COL = STUFF(
(
SELECT DISTINCT ',[' + ISNULL(COL2,'NO_VAL') + ']'
FROM TableName C
FOR XML PATH('')
), 1, 1, '')
EXEC
('
SELECT Series,' + @PIV_COL + '
FROM (
SELECT Series,
ISNULL(COL2,''NO_VAL'') col2,
price
FROM TableName ) AS SourceTable
PIVOT ( SUM(price) FOR col2 IN ('+ @PIV_COL + ')
) AS PivotTable
')