我试图为两个问题找到一个优雅的解决方案: 我对这两个问题的SELECT部分都有疑问。 查询的另一部分很好
从理论上讲,这些问题使没有可用的数据库运行。
第一季度:提取以下报告:显示每天的累计 最近5天(包括5天)内(移动)“点赞”的次数 将显示5月1日至5月5日的总点赞次数。) 美国以外的地区。
列:
DataTimstamp-5天时间范围的上限总计-的数量 在时间范围Region_US中的点赞次数-国家/地区的点赞次数 ='US'Region_rest-国家<>'US'
的点赞次数第二季度:每天提取创建的用户数和每日更改 与前一天相比。
代码:
SELECT
DATEADD(day, 4, se.date) AS DataTimstamp,
COUNT(se.type_id) AS Total,
COUNT(CASE WHEN lo.country_3_character_code = 'USA' THEN 1 ELSE NULL END) AS 'Region_USA',
COUNT(CASE WHEN lo.country_3_character_code != 'USA' THEN 1 ELSE NULL END) AS 'Region_rest'
FROM system_events se
JOIN location lo ON se.location_id = lo.id
WHERE se.type = 'like'
GROUP BY 1
SELECT u.creation_date AS 'day',
COUNT(IF(day = u.creation_date, u.id, 0)) AS Date_day,
COUNT(IF(day = u.creation_date - interval 1 day , u.id, 0)) AS Date_before,
SUM(SUM(Date_day)-SUM(Date_before)) AS daily_change
FROM user u
GROUP BY 1;
答案 0 :(得分:0)
对于第二季度,我认为您可以使用LAG来获取前一天的信息,例如这个简单的例子:
with cte_table as
(
select * from
(values
('01-Jan-19',1)
,('02-Jan-19',2)
,('03-Jan-19',3)
,('04-Jan-19',4)
,('05-Jan-19',5)
) as t (TheDate,TheValue))
select TheDate, TheValue,
LAG(TheValue,1,0) OVER(ORDER BY TheDate) as Prev_Value
from cte_table;
答案 1 :(得分:0)
最近5季度的Q1中,我对此进行了讨论,我可能会被SQL Masters吞噬:-o,可能与交叉应用有关,但是在我目前的知识范围之外。
with cte_table as
(
select * from
(values
('01-Jan-19',10)
,('02-Jan-19',20)
,('03-Jan-19',10)
,('04-Jan-19',5)
,('05-Jan-19',10)
,('06-Jan-19',20)
,('07-Jan-19',10)
,('08-Jan-19',10)
,('09-Jan-19',10)
,('10-Jan-19',5)
) as t (TheDate,TheValue))
, cte_table2 as
(
select TheDate, TheValue
,LAG(TheValue,1,0) OVER(ORDER BY TheDate) as Prev_Value1
,LAG(TheValue,2,0) OVER(ORDER BY TheDate) as Prev_Value2
,LAG(TheValue,3,0) OVER(ORDER BY TheDate) as Prev_Value3
,LAG(TheValue,4,0) OVER(ORDER BY TheDate) as Prev_Value4
from cte_table
)
select TheDate
,sum(TheValue) as current_day
, sum(TheValue) + sum(Prev_Value1) + sum(Prev_Value2) + sum(Prev_Value3) + sum(Prev_Value4) as [last 5 days]
from cte_table2
group by TheDate
order by TheDate
;