我在预订表中有如下所示的数据集
oldornewapp
我正在尝试输出显示基于每个客户的 custid MaxApptDateOldApp MaxapptDatenewapp
---------------------------------------------
100 01-jan-2014 12-oct-2016
200 01-feb-2015 10-oct-2016
列的最长日期
{{1}}
请告诉我获取结果集的最佳方法,我使用的是SQL Server 2012
提前致谢
答案 0 :(得分:1)
SELECT
Custid
,MAX(CASE WHEN oldornewApp = 'old' THEN ApptDate END) as MaxApptDateOldApp
,MAX(CASE WHEN oldornewApp = 'new' THEN ApptDate END) as MaxApptDateNewApp
FROM
TableName
GROUP BY
Custid
您可以使用条件聚合来获得所需的结果。
答案 1 :(得分:0)
您可以使用
加入和分组select old.Custid, max(old.ApptDate) as MaxApptDateOldApp, max(new.ApptDate) as MaxApptDateNewApp
from my_table as old
where a.oldornewApp = 'old';
group by a,Custid
inner join (
select b.Custid, max(b.ApptDate) as AppDate
from my_table as b
where b.oldornewApp = 'new';
group by b.Custid
) new