简体   繁体   English

如何在PostgreSQL中获取列值的计数

[英]How to get the count of column value in postgresql

I have two tables First one with Status, deviceSerial columns.Status be in (1,2,3,4,5). 我有两个表第一个是Status,deviceSerial列.Status位于(1,2,3,4,5)中。 I want to get the result as count of status 我想获得结果作为状态计数

for example device one want to get how many records in status 1, status 2, status 3, status 4, status 5 in a single row 例如,设备一要获取一行中状态1,状态2,状态3,状态4,状态5的记录数量

here is my first table 这是我的第一张桌子

在此处输入图片说明

here is my second table 这是我的第二张桌子

在此处输入图片说明

I want to get these records to result as 我想得到这些记录作为

在此处输入图片说明

Here is the code I tried 这是我尝试的代码

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"

what is the mistake I have done in this problem,please help me 我在这个问题上犯了什么错误,请帮助我

Use pivoting logic: 使用透视逻辑:

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;

You can try below using conditional aggregation 您可以在下面尝试使用条件聚合

select deviceserial,
       count(case when statusid=1 then 1 end) as Permitted ,
       count(case when statusid=2 then 1 end) as IssuedToday,
       count(case when statusid=3 then 1 end) as Permitted ,
       count(case when statusid=4 then 1 end) as InvalidVehicle,
       count(case when statusid=5 then 1 end) as ExpiredOrNotPaid ,
       count(case when statusid=6 then 1 end) as Failed ,
       count(case when statusid=7 then 1 end) as Other
from firstTtable
group by deviceserial

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM