使用SQLite的新手。在构建查询时需要一些帮助。
基本上,我需要按类别分组的月度总计。现在所有3个间隔显示在同一列上。我希望每个区间显示为它自己的单独列。我该怎么办呢?
SELECT tickets.category AS 'Category', count(id) AS 'Interval'
FROM tickets
WHERE strftime('%Y-%m-%d',tickets.created_at) >= date('now','-30 days')
AND strftime('%Y-%m-%d',tickets.created_at)<= date('now', '-7 days')
GROUP BY tickets.category
UNION ALL
SELECT tickets.category AS 'Category', count(id)
FROM tickets
WHERE strftime('%Y-%m-%d',tickets.created_at) >= date('now','-60 days')
AND strftime('%Y-%m-%d',tickets.created_at)<= date('now', '-31 days')
GROUP BY tickets.category
UNION ALL
SELECT tickets.category AS 'Category', count(id)
FROM tickets
WHERE strftime('%Y-%m-%d',tickets.created_at) >= date('now','-90 days')
AND strftime('%Y-%m-%d',tickets.created_at)<= date('now', '-61 days')
GROUP BY tickets.category
ORDER BY tickets.category DESC
答案 0 :(得分:1)
这称为条件聚合。使用where
中的count
条件将它们作为单独的列。
SELECT category
,count(case when strftime('%Y-%m-%d',created_at) >= date('now','-30 days')
AND strftime('%Y-%m-%d',created_at)<= date('now', '-7 days') then id end) as days_7_30
,count(case when strftime('%Y-%m-%d',created_at) >= date('now','-60 days')
AND strftime('%Y-%m-%d',created_at)<= date('now', '-31 days') then id end) as days_31_60
,count(case when strftime('%Y-%m-%d',created_at) >= date('now','-90 days')
AND strftime('%Y-%m-%d',created_at)<= date('now', '-61 days') then id end) as days_61_90
FROM tickets
GROUP BY category