有人会帮我介绍如何使用基本SQL添加组列吗?我使用Teradata SQL Assistant。
我的数据集是这样的:
mydate color mytime
----------------------------
9/1/2017 red 1:00
9/1/2017 red 2:00
9/1/2017 red 3:00
9/1/2017 red 4:00
9/1/2017 yellow 5:00
9/1/2017 yellow 6:00
9/1/2017 red 7:00
9/1/2017 red 8:00
9/1/2017 yellow 9:00
9/1/2017 yellow 10:00
9/1/2017 yellow 11:00
9/1/2017 yellow 12:00
9/1/2017 red 13:00
9/1/2017 red 14:00
9/1/2017 red 15:00
9/1/2017 yellow 16:00
9/1/2017 yellow 17:00
我想要的结果(添加专栏" mygroup"):
mydate color mygroup mytime
----------------------------------
9/1/2017 red 1 1:00
9/1/2017 red 1 2:00
9/1/2017 red 1 3:00
9/1/2017 red 1 4:00
9/1/2017 yellow 2 5:00
9/1/2017 yellow 2 6:00
9/1/2017 red 3 7:00
9/1/2017 red 3 8:00
9/1/2017 yellow 4 9:00
9/1/2017 yellow 4 10:00
9/1/2017 yellow 4 11:00
9/1/2017 yellow 4 12:00
9/1/2017 red 5 13:00
9/1/2017 red 5 14:00
9/1/2017 red 5 15:00
9/1/2017 yellow 6 16:00
9/1/2017 yellow 6 17:00
答案 0 :(得分:1)
select
mydate
,color
,mytime
-- then create the group number
,sum(flag)
over (order by mydate, mytime
rows unbounded preceding) as mygroup
from
(
select
mydate
,color
,mytime
-- first: find the row where the color changes
-- previous row is different from current row
,case when min(color)
over (order by mydate, mytime
rows between 1 preceding and 1 preceding) = color
then 0
else 1
end as flag
from mytable
) as dt
MIN(color)
计算是LAG
函数的仿真,在TD16.10之前Teradata中没有这种函数。