[英]2 column with same ID to 1 row
I have a table with only 2 column which is as follow 我有一个只有2列的表,如下
|ID | Date |
===================
|1 | 03/04/2017 |
|1 | 09/07/1997 |
|2 | 04/04/2014 |
I want to achieve an end result as follow 我想取得最终结果如下
|ID | Date 1 |Date 2 |
================================
|1 | 03/04/2017 | 09/07/1997 |
|2 | 04/04/2014 | NULL |
I'm currently reading up on PIVOT function and I'm not sure am I on the right track. 我目前正在阅读PIVOT功能,但不确定自己是否走对了。 Am still new to SQL
还是SQL新手
A simple pivot query should work here, with a twist. 一个简单的透视查询应该可以在这里工作,但要有所不同。 For your
ID
2 data, there is only one row, but in this case you want to report a first date and a NULL
second date. 对于您的
ID
2数据,只有一行,但是在这种情况下,您要报告第一个日期和NULL
第二个日期。 We can use a CASE
expression to handle this case. 我们可以使用
CASE
表达式来处理这种情况。
SELECT
ID,
MAX(Date) AS date_1,
CASE WHEN COUNT(*) = 2 THEN MIN(Date) ELSE NULL END AS date_2
FROM yourTable
GROUP BY ID
Output: 输出:
Demo here: 演示在这里:
This can be done easily using min/max
aggregate function 使用
min/max
聚合函数可以轻松完成此操作
select Id,min(Date),
case when min(Date)<>max(Date) then max(Date) end
From yourtable
Group by Id
If this will not help you with your original data, then alter sample data and expected result 如果这样做对您的原始数据无济于事,请更改样本数据和预期结果
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.