sqlite—包含空值和不在列表中的值的sql聚合语句

2w3rbyxf  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(294)


结果我要找的是一个表格,每个城市,独特的赞成票的数量,总赞成票。如果投票表中有不属于用户表中某个城市的yes投票,则需要返回具有相同聚合统计信息的“other city”。结果应该是。。。

CREATE TABLE users (
    user_id NUMERIC,
    city   STRING
);

insert into users (user_id, city)
values 
 (1, "nyc"),
 (2, "den"),
 (3, "nyc"),
 (4, "atl")

CREATE TABLE votes (
    sub_id,
    user_id,
    vote
);

insert into votes (sub_id, user_id, vote)
values
 (57, 1, "yes"),
 (57, 2, "yes"),
 (57, 5, "yes"),
 (57, 6, "no"),
 (58, 4, "no"),
 (58, 10, "no"),
 (58, 2, "yes"),
 (59, 12, "no");
mrfwxfqh

mrfwxfqh1#

你需要一个 LEFT 连接 votesusers 和条件聚合:

select coalesce(u.city, 'other city') city, 
       count(distinct case when vote = 'yes' then v.user_id end) unique_yes,
       sum(vote = 'yes') total_yes
from votes v left join users u
on v.user_id = u.user_id
group by u.city
order by u.city is null, u.city

请看演示。
结果:

| city       | unique_yes | total_yes |
| ---------- | ---------- | --------- |
| atl        | 0          | 0         |
| den        | 1          | 2         |
| nyc        | 1          | 1         |
| other city | 1          | 1         |
nnsrf1az

nnsrf1az2#

你应该使用 LEFT JOIN 在你的table之间 unique_yes 列应使用 DISTINCT 为了实现你的目标。

SELECT CASE WHEN USERS.CITY IS NOT NULL THEN USERS.CITY ELSE 'other city' END CITY,
         COUNT (
            DISTINCT CASE WHEN VOTES.VOTE = 'yes' THEN VOTES.VOTE ELSE NULL END)
            UNIQUE_YES,
         COUNT (CASE WHEN VOTES.VOTE = 'yes' THEN VOTES.VOTE ELSE NULL END)
            TOTAL_YES
    FROM VOTES LEFT JOIN USERS ON USERS.USER_ID = VOTES.USER_ID
GROUP BY CASE WHEN USERS.CITY IS NOT NULL THEN USERS.CITY ELSE 'other city' END

演示

相关问题