说有这张桌子: https://www.db-fiddle.com/f/9xw9aPa42MfuqnxDb3bWvN/2
如何编写SQL请求以获取: 某个用户的总行数及其百分比(具有某些状态的行占总行数)。
例如:
对于user_id = 1和status = true:
总数= 3 prc = 33%(计数为2的状态为真)
答案 0 :(得分:1)
有条件聚合:
SELECT
ROUND(100 * AVG(CASE WHEN state THEN 1 ELSE 0 END), 1) prc,
COUNT(*) counter
FROM test_query
WHERE partnerSteamid64='uuid_1'
请参见demo。
结果:
| prc | counter |
| ---- | ------- |
| 25.0 | 4 |
答案 1 :(得分:0)
使用简单的sql语法
select count(*), count(*)*100.0/(select count(*) from test_query) from test_query where partnerSteamid64 = 'uuid_1' and state = true
根据您的需求在主查询和子查询中修改where条件
答案 2 :(得分:0)
我认为最简单的方法是条件聚合:
SELECT user_id, count(*),
avg( status::int ) as ratio
FROM some_table
GROUP BY user_id
要计算false
个值:
avg( (not status)::int ) as ratio