簡體   English   中英

postgres 分組結果

[英]postgres group by in result

我需要計算每輛車的事故數量(100,200,300,400+),並計算每組的汽車數量,例如:

事件總數 汽車數量
100 34
200 43
300 12
400+ 412

我嘗試運行下面的代碼,但結果只有 400+ 和汽車總數,我看不到結果中的所有組。

SELECT
case
when count(incidents) > 400 then '400+' else count(incidents)::Text END Total_number_of_incidents,
count(distinct car) as number_of_cars
from car_incidents

我會聚集兩次,第一次是開車,然后是一切。 另外,如果你在不同的列而不是不同的行中得到結果,你只需要掃描表一次。

SELECT count(*) FILTER (WHERE incidents >= 400) AS "400+",
SELECT count(*) FILTER (WHERE incidents >= 300 AND incidents < 400) AS "300",
SELECT count(*) FILTER (WHERE incidents >= 200 AND incidents < 300) AS "200",
SELECT count(*) FILTER (WHERE incidents >= 100 AND incidents < 200) AS "100"
FROM (SELECT car, count(*) AS incidents
      FROM car_incidents
      GROUP BY car) AS subq;

在您的查詢中,您計算事件。 沒有GROUP BY子句,因此您會得到一個帶有計數的結果行。 您計算此計數,如果它大於 400,您將顯示 400+ 而不是實際計數。

您想要多個結果行,所以您想要計算每個 __________ 的事件? 或者你想數一數還是只數一數? incidents不是已經是汽車發生事故的次數了嗎?

也許,只是也許,你想要這個:

select
  case when incidents > 400 then '400+' else incidents::Text as total_number_of_incidents,
  count(*) number_of_cars
from car_incidents
group by case when incidents > 400 then '400+' else incidents::Text;

雖然這可能不是您想要的,但也許這個答案會將您帶到您真正想要的地方 go。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM