我需要在sql中执行以下操作。
表1:
Year Client Investment
1999 X 100
1999 Y 200
2000 X 1000
2000 Y 2000
我想在我的报告中以以下格式显示它:
Client 1999Year 2000Year
X 100 1000
你知道怎么做吗?
我正在使用SQL Server 2008
请帮忙。
最佳答案
有很多可能的解决方案。一种是使用MAX()
和CASE
,
SELECT Client,
MAX(CASE WHEN YEAR = 1999 THEN Investment END) [1999Year],
MAX(CASE WHEN YEAR = 2000 THEN Investment END) [2000Year]
FROM TableName
WHERE Client = 'X'
GROUP BY Client
SQLFiddle Demo
或使用
PIVOT
函数SELECT Client,
[1999] AS [1999YEAR],
[2000] AS [2000YEAR]
FROM
(
SELECT YEAR, CLient, Investment
FROM TableName
WHERE Client = 'X'
) pvt
PIVOT
(
MAX(InvestMent)
FOR YEAR IN ([1999],[2000])
) s
SQLFiddle Demo
关于sql - 将值从一列拆分为两列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15479001/