我有一个数据表历史记录。我想生成我需要的图表,
根据选定的期间类型显示图表上的值。
使用以下的sql代码,我可以获取last entry per day
。
SELECT t.created_on,
t.earned_value,
t.planned_value,
t.budgeted_cost
FROM history t
JOIN (SELECT MAX(tt.created_on) 'maxtimestamp'
FROM history tt
GROUP BY date(tt.created_on)) m ON m.maxtimestamp = t.created_on
如何获得其他三个结果?
答案 0 :(得分:1)
您可以使用window function:
非常优雅地解决这个问题SELECT created_on, earned_value, planned_value, budgeted_cost
FROM (
SELECT created_on, earned_value, planned_value, budgeted_cost,
rank() OVER (PARTITION BY extract(year from created_on),
extract(doy from created_on)
ORDER BY created_on DESC) r
FROM history) sub
WHERE r = 1
ORDER BY created_on;
对于周和月的时间段,您只需将extract(doy from created_on)
参数更改为extract(week ...
(doy =一年中的某一天,从1月1日算起)。对于年度数据,您只需要第一个extract()
,因此您应该删除第二个PARTITION
字词。
答案 1 :(得分:0)
EXTRACT(WEEK FROM tt.created_on), EXTRACT(month FROM tt.created_on),EXTRACT(year FROM tt.created_on)
成功了。
SO,
1-每天的最后一次入场
SELECT t.created_on,
t.earned_value,
t.planned_value,
t.budgeted_cost
FROM history t
JOIN (SELECT MAX(tt.created_on) 'maxtimestamp'
FROM history tt
GROUP BY EXTRACT(DAY FROM tt.created_on)) m ON m.maxtimestamp = t.created_on
2-每周最后一次入场
SELECT t.created_on,
t.earned_value,
t.planned_value,
t.budgeted_cost
FROM history t
JOIN (SELECT MAX(tt.created_on) 'maxtimestamp'
FROM history tt
GROUP BY EXTRACT(WEEK FROM tt.created_on)) m ON m.maxtimestamp = t.created_on
3-每个月的最后一个条目
SELECT t.created_on,
t.earned_value,
t.planned_value,
t.budgeted_cost
FROM history t
JOIN (SELECT MAX(tt.created_on) 'maxtimestamp'
FROM history tt
GROUP BY EXTRACT(MONTH FROM tt.created_on)) m ON m.maxtimestamp = t.created_on
4-每年的最后一次进入
SELECT t.created_on,
t.earned_value,
t.planned_value,
t.budgeted_cost
FROM history t
JOIN (SELECT MAX(tt.created_on) 'maxtimestamp'
FROM history tt
GROUP BY EXTRACT(YEAR FROM tt.created_on)) m ON m.maxtimestamp = t.created_on