如何显示每周发生并满足某些条件的记录总数 SQL
Posted
技术标签:
【中文标题】如何显示每周发生并满足某些条件的记录总数 SQL【英文标题】:How to display total number of records that occured each week and met some conditions SQL 【发布时间】:2020-12-15 10:05:43 【问题描述】:能否请您帮我编写一个 SQL 查询,该查询将返回有关每周发生的升级次数以及与前一周相比的变化的信息。 最终结果应该只显示现有用户的数据。
表格示例:
PROJECT ID EVENT DATE EVENT TYPE USER_TYPE
1 01012020 upgrade existing
2 02012020 downgrade new
3 04012020 upgrade existing
1 05012020 upgrade existing
2 07012020 downgrade new
3 08012020 upgrade existing
1 09012020 downgrade existing
2 1012020 upgrade new
我想做的事:
SELECT
DATEPART(week, event_date) As Week,
COUNT(PROJECT_IS)
FROM Customers
GROUP BY DATEPART(week, event_date)
ORDER BY DATEPART(week, event_date);
但我不知道如何在此处包含 if 语句 + 我应该只为现有用户显示结果。 我对 SQL 很陌生,所以欢迎提出任何建议。 谢谢
预期结果:
USER_TYPE EVENT_TYPE NUMBER_OF_UPGRADES WEEK DIF_WEEK
existing upgrade (total number of upgrades) Week 1 Week1
existing upgrade (total number of upgrades) Week 2 Week2-Week1
【问题讨论】:
也请分享预期结果。并尽量避免将图像用于样本数据和预期结果 Datepart 是一个 t-sql/sqlserver 函数 - mysql t-sql,这个问题标记正确吗? 【参考方案1】:对于existing
用户,可以使用以下查询获得每周升级次数:
SELECT 'existing' AS USERTYPE,
'upgraded' AS EVENT_TYPE,
COUNT(1),
DATEPART(week, event_date) As Week
FROM Customers
WHERE user = 'existing' and event_type = 'upgraded' -- conditions here
GROUP BY DATEPART(week, event_date)
ORDER BY DATEPART(week, event_date);
【讨论】:
【参考方案2】:假设您使用的是 SQL Server,那么您需要这样的东西:
SELECT user, event_type,
YEAR(event_date) as year, DATEPART(week, event_date) As Week
COUNT(*) as this_week
COUNT(*) - LAG(COUNT(*)) OVER (PARTITION BY user, event_type ORDER BY MIN(event_date)) as diff
FROM Customers
WHERE user = 'existing' and event_type = 'upgraded' -- conditions here
GROUP BY user, event_type, YEAR(event_date), DATEPART(week, event_date)
ORDER BY DATEPART(week, event_date);
注意事项:
对日期要非常小心。没有年份的那一周可能非常危险,所以我将其包含在SELECT
和 GROUP BY
中。
我在SELECT
和GROUP BY
中都包含了user
/event_type
。这样可以轻松显示所有组或更改组。
LAG()
计算两行之间的差异。
【讨论】:
以上是关于如何显示每周发生并满足某些条件的记录总数 SQL的主要内容,如果未能解决你的问题,请参考以下文章