多行结果集合成一行

时间:2014-12-08 07:16:51

标签: sql sql-server sql-server-2008

我有一个结果集的查询如下

编辑:我的不好,我粘贴了错误的架构/结果集,实际看起来像这样

+-----------+------------+-----------+ | Record ID | Date | Note Type | +-----------+------------+-----------+ | XYZ | 12/1/2014 | External | | XYZ | 12/5/2014 | Internal | | XYZ | 12/6/2014 | Internal | | ABC | 11/10/2014 | External | | ABC | 11/15/2014 | Internal | +-----------+------------+-----------+ 我想获得回答问题的输出

  

对于记录第一个内部记事和外部记事是否已添加?

所以在这种情况下,我想要的输出如下

+-----------+---------------+---------------+ | Record ID | External Note | Internal Note | +-----------+---------------+---------------+ | XYZ | 12/1/2014 | 12/5/2014 | | ABC | 11/10/2014 | 11/15/2014 | +-----------+---------------+---------------+

我尝试使用PIVOT实现它但无法获得确切的输出并且有点卡在这个位置,任何帮助都将不胜感激。 感谢

1 个答案:

答案 0 :(得分:1)

试试这个:

select recordid, min([external note]) as [external note], min([internal note]) as [internal note]
from yourtable
group by recordid

假设您的数据遵循示例中显示的模式,上述查询可以在不使用PIVOT的情况下为您提供最小值。

Demo

根据您更新的架构,您仍然可以在没有数据透视的情况下执行此操作,如下所示:

;with cte_ext as
(select recordid as erid, min([date]) as minext
from yourtable
where [Note type] = 'External'
group by recordid),
cte_int as
(select recordid as irid, min([date]) as minint
from yourtable
where [Note type] = 'Internal'
group by recordid)

select e.erid as RecordID, e.minext as [External Date], i.minint as [Internal Date]
from cte_ext e
inner join cte_int i on e.erid = i.irid

Demo