SQL- 转置每组一个值的数据
SQL- Transpose data with one value per group
我有不同代码和关联日期的项目。对于代码 P 和 L,我想 return 与代码关联的最小日期作为新列。对于代码 D,我想 return 最大日期作为新列。我的数据如下所示:
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
想要的结果是这样的:
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
所以每一项都有一行,代码P和L显示最小值,代码D显示最大值。任何想法如何去做这个?我正在使用 Teradata。谢谢!
只使用条件聚合:
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;
我有不同代码和关联日期的项目。对于代码 P 和 L,我想 return 与代码关联的最小日期作为新列。对于代码 D,我想 return 最大日期作为新列。我的数据如下所示:
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
想要的结果是这样的:
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
所以每一项都有一行,代码P和L显示最小值,代码D显示最大值。任何想法如何去做这个?我正在使用 Teradata。谢谢!
只使用条件聚合:
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;