[英]SQL- Transpose data with one value per group
I have items with different codes and dates associated with them. 我有与它们相关的代码和日期不同的项目。 For codes P and L, I want to return the min date associated with the code as a new column. 对于代码P和L,我想将与代码关联的最小日期作为新列返回。 For code D, I want to return the max date as a new column. 对于代码D,我想将最长日期作为新列返回。 My data looks like this: 我的数据如下所示:
Item Code Date
ABC P 11/24/2017 13:01
ABC L 11/24/2017 16:30
ABC P 11/25/2017 12:30
ABC L 11/25/2017 20:24
ABC D 11/26/2017 21:34
ABC D 11/26/2017 23:16
ABD P 10/5/2017 9:30
ABD L 10/5/2017 13:23
ABD L 10/6/2017 3:04
ABD D 10/7/2017 8:31
The desired result is this: 理想的结果是这样的:
Item Code_P Code_L Code_D
ABC 11/24/2017 13:01 11/24/2017 16:30 11/26/2017 23:16
ABD 10/5/2017 9:30 10/5/2017 13:23 10/7/2017 8:31
So each item has one line, with Codes P and L showing the minimum value, and Code D having the maximum. 因此,每一项都有一行,其中代码P和L表示最小值,代码D表示最大值。 Any ideas how to go about this? 任何想法如何去做? I'm using Teradata. 我正在使用Teradata。 Thanks! 谢谢!
Just use conditional aggregation: 只需使用条件聚合:
select item,
max(case when code = 'P' then date end) as p_date,
max(case when code = 'L' then date end) as l_date,
max(case when code = 'D' then date end) as s_date
from t
group by item;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.