使用基本 SQL 对组进行排名
Rank groups using basic SQL
有人会教我如何使用基本 SQL 添加组列吗?我使用 Teradata SQL 助手。
我的数据集是这样的:
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
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 中不可用。
有人会教我如何使用基本 SQL 添加组列吗?我使用 Teradata SQL 助手。
我的数据集是这样的:
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
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 中不可用。