我有这个数据:
CREATE TABLE tickets(user_id int NOT NULL);
INSERT INTO tickets VALUES (1);
INSERT INTO tickets VALUES (2);
INSERT INTO tickets VALUES (3); -- 3 times
INSERT INTO tickets VALUES (4); -- 10 times
现在我想显示每个用户的票数百分比。
我试过这个:
WITH number_of_tickets AS (
SELECT user_id, COUNT(user_id) AS number_of_tickets_per_user
FROM tickets
GROUP BY user_id
)
SELECT
number_of_tickets_per_user,
ROUND((COUNT(user_id) * 100.0) / (SELECT COUNT(DISTINCT(user_id)) FROM tickets), 3) -- No no no no
FROM number_of_tickets
GROUP BY number_of_tickets_per_user
ORDER BY number_of_tickets_per_user;
但我可能不能很好地处理百分比计算。结果总是显示每个用户每张票数的 25%。
谢谢
我建议使用窗口函数: