繁体   English   中英

SQL-多行一列变为多行一列

[英]SQL - multiple rows with one column into one row with multiple columns

我有以下查询:

select convert(varchar(32),tas.complete_by_dt,101)+': '+tas.notes [Task] 
from TX_SOL_TASK tas where customer_no=230459

它为每个值返回一行,而我希望每个值只包含一行。 这是当前返回的内容:

Task

08/07/2013: Called Jane for lunch of she is in town

08/19/2013: Jane is NY and will talk with her acct the end of August. Will know then escat amount and hoping by the end of 1st qtr.

09/09/2013: Jane called and requested info to send her check through Fidelity. She is at Canyon Ranch this week. Emailed her info.

09/24/2013: Thank you!

11/06/2013: Called Jane for lunch with MD and mf, she is trasveling after this week. Call her 12/9 to see if we can do that week!

11/13/2013: Sent Jane happy thought for another sucessful Hats in The Garden!

尝试以下动态枢纽:

DECLARE @customer_no INT = 230459;

DECLARE @sql NVARCHAR(MAX) = N'', @cols NVARCHAR(MAX) = N'';

SELECT @cols += STUFF((SELECT ',' + QUOTENAME(CONVERT(VARCHAR(32),complete_by_dt,101))
                       FROM dbo.TX_SOL_TASK 
                       WHERE customer_no = @customer_no
                       GROUP BY CONVERT(VARCHAR(32),complete_by_dt,101)
                       FOR XML PATH('')), 1, 1, '');

SET @sql = N'SELECT *
  FROM (SELECT  CONVERT(VARCHAR(32),complete_by_dt,101) Completed,
                notes
        FROM dbo.TX_SOL_TASK
        WHERE customer_no = @customer_no
        ) AS d
  PIVOT (MIN([notes]) FOR [Completed] IN (' + @cols + ')) AS p;';

EXEC sp_executesql @sql, N'@customer_no INT', @customer_no;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM