所以我有一张这样的表
id | user_id | point | created_at
-------------------------------------------
1 | 1 | 10 | 2015-08-03 00:08:25
2 | 3 | 20 | 2015-08-01 00:08:25
3 | 4 | 30 | 2015-08-13 00:08:25
4 | 3 | 10 | 2015-08-25 00:08:25
5 | 2 | 20 | 2015-09-02 00:08:25
6 | 1 | 10 | 2015-09-14 00:08:25
7 | 4 | 50 | 2015-09-22 00:08:25
8 | 2 | 80 | 2015-09-30 00:08:25
9 | 1 | 30 | 2015-10-02 00:08:25
10 | 5 | 90 | 2015-10-02 00:08:25
我可以生成一个查询来制作这样的结果吗?
start_date | end_date | total_point_100_or_more | total_point_less_than_100
------------------------------------------------------------------------------
2015-08-01 | 2015-08-10 | 3 User | 7 User
2015-08-11 | 2015-08-20 | 8 User | 5 User
2015-08-21 | 2015-08-30 | 10 User | 5 User
2015-08-31 | 2015-09-09 | 4 User | 6 User
我现在没有任何代码,因为我完全不知道从哪里开始。
答案 0 :(得分:0)
我还没有对此进行过测试,因为您的示例答案与您的示例数据不对应,但是非常类似以下内容应该有效。在这里,我假设你想知道用户如何获得高于或低于100的总分(在每个时期)。
SELECT start_date,
DATEADD(day, 9, start_date) as end_date,
SUM(CASE WHEN period_points >= 100 THEN 1 ELSE 0 END) as total_point_100_or_more,
SUM(CASE WHEN period_points < 100 THEN 1 ELSE 0 END) as total_point_less_than_100
FROM (
SELECT start_date,
user_id,
SUM(point) as period_points
FROM (
SELECT DATEADD(
day,
DATEDIFF(day, '2015-08-01 00:00:00', created_at)/10*10,
'2015-08-01 00:00:00'
) as start_date,
id,
user_id,
point
FROM points
) AS p
GROUP BY start_date, user_id
) as q
GROUP BY start_date
请注意,我没有将整数计数转换为文本并附加&#34;用户&#34;如你的样本。