You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于STUFF、UNPIVOT和GROUP BY子句的SQL数据转换需求

Solution Using UNPIVOT, GROUP BY, and STUFF

Got it, let's tackle this problem step by step. Here's the SQL query that meets your requirement—it will unpivot the columns, group by Id and the unique date, then concatenate the corresponding column names into a comma-separated list:

SELECT 
    Id,
    DisclosureDate,
    STUFF(
        (SELECT ', ' + Column_Name
         FROM UnpivotedData ud
         WHERE ud.Id = main.Id AND ud.DisclosureDate = main.DisclosureDate
         FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)'),
        1, 2, ''
    ) AS AssociatedColumns
FROM (
    SELECT 
        Id,
        Column_Name,
        DisclosureDate
    FROM YourTableName
    UNPIVOT (
        DisclosureDate FOR Column_Name IN (
            [Disclosure],
            [Photo Disclosure],
            [Community Trip Disclosure],
            [Assum Of Risk Disclosure],
            [Release Of Info],
            [Photo DisclosureDate]
        )
    ) AS UnpivotResult
) AS UnpivotedData main
GROUP BY Id, DisclosureDate
ORDER BY Id, DisclosureDate;

Let me break down how this works:

  1. UNPIVOT Step: The inner query takes your original table and converts each of the date columns into individual rows. Each row now has the Id, the name of the original column (Column_Name), and its corresponding date (DisclosureDate).
  2. Grouping: We group the unpivoted data by Id and DisclosureDate—this ensures we're handling all columns that share the same date for a specific record.
  3. String Concatenation: The STUFF function paired with FOR XML PATH('') takes all the Column_Name values in each group and joins them into a single comma-separated string. The STUFF removes the leading , that would otherwise be at the start of the string.

Example Output (using your sample data):

IdDisclosureDateAssociatedColumns
12017-05-03Disclosure, Photo Disclosure, Community Trip Disclosure, Assum Of Risk Disclosure, Release Of Info, Photo DisclosureDate
22017-05-03Disclosure, Photo Disclosure, Community Trip Disclosure, Assum Of Risk Disclosure, Release Of Info, Photo DisclosureDate

Just replace YourTableName with the actual name of your table, and you're good to go!

内容的提问来源于stack exchange,提问作者Ram Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:53:29