针对两个不同的类别优化 SQL - Postgres

Optimize SQL for two different category - Postgres

我有一个 table 看起来像

用户名 来源 心率 呼吸频率
uuid 100 67 20
uuid 200 67 24
uuid 100 67 21
uuid 200 67 19
uuid 100 69 25
uuid 200 69 22
uuid 200 69 23
(select
    "UserId",
    "Source",
    avg(case when "HeartRate" > 0 then "HeartRate" end)::int as "HeartRate",
    avg(case when "BreathRate" > 0 then "BreathRate" end)::int as "BreathRate"
    from vitals
    where "UserId"='66fd490f-4d93-47d1-bc65-085f676bdaf2' and "Source"=200
    group by "UserId", "Source" order by "UserId")
    union
(select
    "UserId",
    "Source",
    avg(case when "HeartRate" > 0 then "HeartRate" end)::int as "HeartRate",
    avg(case when "BreathRate" > 0 then "BreathRate" end)::int as "BreathRate"
    from vitals
    where "UserId"='66fd490f-4d93-47d1-bc65-085f676bdaf2' and "Source"=100
    group by "UserId", "Source" order by "UserId")

如果有 2 个不同的来源,则上述查询会产生 2 个结果。一个用于 Source=100,另一个用于 Source=200。结果中的行数应该(假设有足够的数据可用)等于不同 Source 值的数量。

如何更改上述查询,使其不依赖于 Source

的多重选择和静态值的联合

你可以这样做:

select
    "UserId",
    "Source",
    avg(case when "HeartRate" > 0 then "HeartRate" end) :: int as "HeartRate",
    avg(case when "BreathRate" > 0 then "BreathRate" end) :: int as "BreathRate"
from vitals
where
    "UserId" = '66fd490f-4d93-47d1-bc65-085f676bdaf2'
    and "Source" IN(100, 200)
group by "UserId","Source"
order by "UserId"

只去掉过滤条件:

select "UserId", "Source",
       avg(case when "HeartRate" > 0 then "HeartRate" end)::int as "HeartRate",
       avg(case when "BreathRate" > 0 then "BreathRate" end)::int as "BreathRate"
from vitals
where "UserId" = '66fd490f-4d93-47d1-bc65-085f676bdaf2' 
group by "UserId", "Source"
order by "UserId", "Source";

如果您需要特定来源,可以使用 and Source" in (100, 200, . . . )`。