gpt4 book ai didi

sql - 如何在postgresql中获取列值的计数

转载 作者:行者123 更新时间:2023-11-29 12:32:00 24 4
gpt4 key购买 nike

我有两张 table 第一个状态,deviceSerial columns.Status 在(1,2,3,4,5)。我想得到状态计数的结果

例如设备一想要获取一行中状态1、状态2、状态3、状态4、状态5的记录数

这是我的第一张 table

enter image description here

这是我的第二张 table

enter image description here

我想让这些记录的结果为

enter image description here

这是我试过的代码

Select "deviceSerial",  (select count("statusId")as Permitted from public.scan_track
where "statusId" = 1 group by "statusId"),

(select count("statusId")as IssuedToday from public.scan_track
where "statusId" = 2 group by "statusId"),

(select count("statusId")as PaidForParking from public.scan_track
where "statusId" = 3 group by "statusId"),

(select count("statusId")as InvalidVehicle from public.scan_track
where "statusId" = 4 group by "statusId"),

(select count("statusId")as ExpiredOrNotPaid from public.scan_track
where "statusId" = 5 group by "statusId"),

(select count("statusId")as Failed from public.scan_track
where "statusId" = 6 group by "statusId"),

(select count("statusId")as Other from public.scan_track
where "statusId" = 7 group by "statusId")
from public.scan_track
group by "deviceSerial"

我在这个问题上做错了什么,请帮助我

最佳答案

使用旋转逻辑:

SELECT
deviceSerial,
COUNT(*) FILTER (WHERE statusid = 1) AS Permitted,
COUNT(*) FILTER (WHERE statusid = 2) AS IssuedToday,
COUNT(*) FILTER (WHERE statusid = 3) AS PaidForParking,
COUNT(*) FILTER (WHERE statusid = 4) AS InvalidVehicle,
COUNT(*) FILTER (WHERE statusid = 5) AS ExpiredOnNotPaid,
COUNT(*) FILTER (WHERE statusid = 6) AS Failed,
COUNT(*) FILTER (WHERE statusid = 7) AS Other
FROM scan_track
GROUP BY
deviceSerial;

关于sql - 如何在postgresql中获取列值的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57248217/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com