我正在尝试按行值频率按降序对数据库记录进行排序,但不对条目进行分组。对不起,我是数据库的初学者。
以下是完整代码:
SELECT *
FROM table_name
WHERE date_time >= 10
and date_time <= 100
GROUP BY activity_type
ORDER BY COUNT(activity_type) DESC
以下是相关代码:
SELECT *
FROM table_name
GROUP BY activity_type
ORDER BY COUNT(activity_type) DESC
这是期望的结果(按活动类型的频率按降序排序,不分组):
name (irrelevant) activity_type (number)
------------------------------------------------
Rome 1
London 1
Madrid 1
Stockholm 3
Paris 3
Moscow 2
答案 0 :(得分:2)
不幸的是,SQLite在子查询中不支持group by
。因此,您的选择要么是外连接(它自己创建表的交叉产品,然后用group by
剔除),要么是包含activity_type
计数的临时表。
CREATE TABLE activity_count_table(activity_type, activity_count);
INSERT INTO activity_count_table
SELECT activity_type, COUNT(activity_type) AS activity_count
FROM table_name
WHERE date_time BETWEEN 10 AND 100
GROUP BY activity_type;
SELECT *
FROM table_name NATURAL JOIN activity_count_table
WHERE date_time BETWEEN 10 AND 100
ORDER BY activity_count_table.activity_count DESC;
DROP TABLE activity_count_table;
显然,这不是一个理想的解决方案。您可能希望为每个调用添加一个名称activity_count_table
的唯一标识符(以便多个查询不会相互干扰)。
它仍然比创建外连接(在内存中需要n ^ 2行)然后用group by
剔除它更好(当应用于自连接时,它实际上只是给你一个对角线)。
答案 1 :(得分:1)
如果聚合不得影响实际查询,则必须将其移动到子查询中:
SELECT *
FROM table_name
WHERE date_time BETWEEN 10 AND 100
ORDER BY (SELECT count(*)
FROM table_name AS T2
WHERE T2.activity_type = table_name.activity_type
AND date_time BETWEEN 10 AND 100) DESC;
答案 2 :(得分:0)
如果您的数据库支持它,您可以使用带有OVER
子句的窗口函数,例如
SELECT *
FROM table_name
ORDER BY COUNT(*) OVER (PARTITION BY activity_type) DESC
确认工作: