【问题标题】:Pivoting duplicate data from rows to columns in SQL Server在 SQL Server 中将重复数据从行转移到列
【发布时间】:2020-04-16 19:03:05
【问题描述】:

由于收到的针对特定候选人的反馈数量,我有一个包含重复值的数据集。

有 3 种反馈类型:安全、其他和社交。

候选人可以有多个这样的反馈。并且这个反馈类型名称必须通过加入 Org 和 orgtype 表来获取。但这在我的结果集中给了我重复的值。

列数很少的查询是这样的:

select 
    c.id  as [Candidate ID]
    ,c.name as [Candidate Name]       
    ,cf.status as [feedback status]
    ,e.name as [Feedback Type]
from
    Candidates c
left join
    Candidate_Feedback CF ON CF.CandidateId = c.ID
left join
    Organizations d on CF.OrgId = d.ID
left join 
    OrganizationTypes e on d.OrganizationTypeId = e.Id

如果每个候选人只需要一行,并且反馈类型在列而不是行中,我该如何透视数据? (例如 col1 - Feedback_socialCol2 - Feedback_Othercol3 - Feedback_Security、col4 - 'N/A' (如果没有反馈)

由于我的查询中的其他情况,我需要为每个候选人提供这 3 列。

【问题讨论】:

    标签: sql sql-server database duplicates pivot


    【解决方案1】:

    您可以使用条件聚合,例如:

    select 
        c.id  as [Candidate ID],
        c.name as [Candidate Name]       
        max(case when e.name = 'Social' then cf.status end) [Feedback Social],
        max(case when e.name = 'Other' then cf.status end) [Feedback Other],
        max(case when e.name = 'Security' then cf.status end) [Feedback Security]
    from Candidates c
    left join Candidate_Feedback CF ON CF.CandidateId = c.ID
    left join Organizations d on CF.OrgId = d.ID
    left join OrganizationTypes e on d.OrganizationTypeId = e.Id
    group by c.id, c.name
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-08
      • 2013-01-13
      • 2020-02-18
      • 2010-10-08
      • 2015-07-01
      • 1970-01-01
      • 2011-07-02
      • 2013-06-09
      相关资源
      最近更新 更多