简体   繁体   English

2列具有相同ID的1行

[英]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: 演示在这里:

Rextester 右旋酯

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.

相关问题 获取具有相同行ID的列值 - Get column value with same row id SQL查询用于获取同一行的列中提到的具有其ID的行 - SQL query for fetching rows with their id mentioned in a column of that same row 如果该行的外部ID相同,SQL如何强制列唯一? - SQL how to force column to be unique if that row's foreign ID is the same? 根据列ID(顺序)将所选数据合并到同一行 - Combine selected data into same row based on column id (order) sql - select 行 id 基于同一行中的两个列值作为 id - sql - select row id based on two column values in same row as id 在多行中填充的SQL相同ID具有不同的列值-在一行中需要一个ID - SQL Same ID Populated in Multiple Rows with Different Column Values Populated--Need One ID in One Row MySQL-根据具有相同user_id的其他行的列值,按user_id选择行 - MySQL - select row by user_id based on column value of other rows with the same user_id 通过特定ID删除一行,而另一行没有此特定ID - delete one row by Specific ID which the same is not present another table Column ID 当ID相同时,如何将多行合并为单行,每行数据的列不同 - How to combine multiple rows into single row with different column per row's data when ID is the same 当另一行具有相同的 id 但列中的值不同时,如何在 SQL 中选择一行? - How do I select one row in SQL when another row has same id but a different value in a column?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM