列中的调用历史 SQL SERVER
Posted
技术标签:
【中文标题】列中的调用历史 SQL SERVER【英文标题】:Call history In Columns SQL SERVER 【发布时间】:2015-10-19 12:36:22 【问题描述】:我有一张桌子和
select [Caller ID] , [Call details] from [DEMO].[dbo].[calldetails]
想要多列的结果,如
【问题讨论】:
请查看图片链接了解我的要求 【参考方案1】:您可以使用PIVOT
表运算符来执行此操作:
SELECT
[Caller ID],
[1] AS [Call Details 1],
[2] AS [Call Details 2],
[3] AS [Call Details 3]
FROM
(
SELECT
[Caller ID],
[Call details],
ROW_NUMBER() OVER(PARTITION BY [Caller ID]
ORDER BY [Caller ID]) AS RN
FROM [calldetails]
) AS t
PIVOT
(
MAX([Call details])
FOR RN IN([1], [2], [3])
) AS p;
请注意:
我使用基于Caller ID
生成的行号将通话详细信息分为 3 列。
我按Caller ID
排序结果,因为我必须使用ORDER BY
和PARTITION BY
。这就是为什么您会发现结果的顺序与您要查找的顺序不同。
SQL Fiddle Demo
这会给你:
| Caller ID | Call Details 1 | Call Details 2 | Call Details 3 |
|-----------|-----------------|-----------------|----------------|
| 123 | Ordered Product | Shipped Product | More Details |
| 125 | product search | (null) | (null) |
| 234 | product search | Ordered Product | (null) |
如果您想动态地执行此操作并且不手动列出这些行号列表,您必须像这样动态地执行此操作:
DECLARE @cols AS NVARCHAR(MAX);
DECLARE @colnames AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);
SELECT @cols = STUFF((SELECT distinct ',' +
QUOTENAME(RN)
FROM
(
SELECT ROW_NUMBER() OVER(PARTITION BY [Caller ID]
ORDER BY [Caller ID]) AS RN
FROM [Calldetails]
) AS t
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
, 1, 1, '');
SELECT @colnames = STUFF((SELECT distinct ',' +
QUOTENAME(RN) + 'AS' +
QUOTENAME('[Call details ' + CAST(RN AS NVARCHAR(5)) + ']')
FROM
(
SELECT ROW_NUMBER() OVER(PARTITION BY [Caller ID]
ORDER BY [Caller ID]) AS RN
FROM [Calldetails]
) AS t
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
, 1, 1, '');
SELECT @query = 'SELECT [Caller ID], ' + @colnames +
' FROM
(
SELECT
[Caller ID] ,
[Call details],
ROW_NUMBER() OVER(PARTITION BY [Caller ID]
ORDER BY [Caller ID]) AS RN
FROM [calldetails]
) AS t
PIVOT
(
MAX([Call details])
FOR RN IN(' + @cols + ')' +
') p';
execute(@query);
SQL Fiddle Demo
【讨论】:
非常感谢..:) @SaileshAgarwal - 不客气,如果您觉得有帮助,请尝试接受答案。以上是关于列中的调用历史 SQL SERVER的主要内容,如果未能解决你的问题,请参考以下文章