另一个适合您的SQL Server专家......
我有一张这样的桌子......
AccountManager | Action | Count
-----------------------------------------------------
Joe | Client Negotiation | 10
Bloggs | Closing | 1
Aunty | Email | 12
Marie | Preparing Contract | 32
“操作”列可能有许多不同类型的状态,这些状态可能不一定是固定的。
我需要输出如下:
AccountManager | Client Negotiation | Closing | Email | Preparing Contract
--------------------------------------------------------------------------
Joe | 10 | 0 | 0 | 0
Bloggs | 0 | 1 | 0 | 0
Aunty | 0 | 0 | 12 | 0
Marie | 0 | 0 | 0 | 32
如何实现这一目标?救命啊!
答案 0 :(得分:1)
select [AccountManager], ISNULL([Email],0) as [Email], ISNULL([Closing],0) as [Closing], ISNULL([Preparing Contact],0) as [Preparing Contact], ISNULL([Client Negotiation],0) as [Client Negotiation] from
(SELECT * FROM TestPivot) as SourceTable
Pivot
(
SUM([Count])
For [Action] in ([Email], [Closing], [Preparing Contact], [Client Negotiation])
) as PivotedColumns
order by [Email] desc, [Closing] desc, [Preparing Contact] desc, [Client Negotiation] desc
答案 1 :(得分:1)
也许是这样的:
首先是测试数据:
CREATE TABLE #tbl (AccountManager VARCHAR(100), Action VARCHAR(100),Count INT)
INSERT INTO #tbl
VALUES
('Joe','Client Negotiation',10),
('Bloggs','Closing',1),
('Aunty','Email',12),
('Marie','Preparing Contract',32)
如果您知道列是静态的。然后你可以这样做:
SELECT
AccountManager,
ISNULL([Client Negotiation],0) AS [Client Negotiation],
ISNULL([Closing],0) AS [Closing],
ISNULL([Email],0) AS [Email],
ISNULL([Preparing Contract],0) AS [Preparing Contract]
FROM
(
SELECT
tbl.AccountManager,
tbl.Action,
tbl.Count
FROM
#tbl AS tbl
) AS p
PIVOT
(
SUM([Count])
FOR [Action] IN([Client Negotiation],[Closing],[Email],[Preparing Contract])
) AS pvt
否则你必须像这样做一个动态支点:
首先是唯一的列名:
DECLARE @cols VARCHAR(MAX),
@colsWithIsNull VARCHAR(MAX)
;WITH CTE
AS
(
SELECT
ROW_Number() OVER(PARTITION BY tbl.Action ORDER BY tbl.Action) AS iRank,
tbl.Action
FROM
#tbl AS tbl
)
SELECT @cols = COALESCE(@cols + ','+QUOTENAME(Action),
QUOTENAME(Action)),
@colsWithIsNull=COALESCE(@colsWithIsNull + ',ISNULL('+QUOTENAME(Action)+',0) AS '+QUOTENAME(Action),
'ISNULL('+QUOTENAME(Action)+',0) AS '+QUOTENAME(Action))
FROM
CTE
WHERE
iRank=1
那么动态支点如下:
DECLARE @query NVARCHAR(4000)=
N'SELECT
AccountManager,
'+@colsWithIsNull+'
FROM
(
SELECT
tbl.AccountManager,
tbl.Action,
tbl.Count
FROM
#tbl AS tbl
) AS p
PIVOT
(
SUM([Count])
FOR [Action] IN('+@cols+')
) AS pvt'
EXECUTE(@query)
然后在我的情况下,我将删除临时表:
DROP TABLE #tbl
答案 2 :(得分:0)
最好由您正在使用的报告工具处理。寻找“数据透视表”。
答案 3 :(得分:0)