簡體   English   中英

使用 A 列對記錄進行計數和分組,並使用 where 子句對 B 列進行計數

[英]Count & group records with column A and do a count on column B with where clause

我有一個名為arb_visits的表,其中包含country & clicked列。 我正在嘗試創建一個查詢,按country /地區對visits進行分組,並獲取clicked count為 1 的次數。

我設法單獨創建了查詢,但在組合它們時遇到了問題。

我設法通過以下方式獲得國家及其數量:

SELECT country, count(*) as visits 
FROM arb_visits 
GROUP BY country 
ORDER BY visits DESC

其中給出以下 output:

[
  {
    "country": "United States",
    "visits": 113,
    "id": null
  },
  {
    "country": "Canada",
    "visits": 85,
    "id": null
  },
  {
    "country": "Germany",
    "visits": 84,
    "id": null
  }
]

點擊也一樣:

SELECT country, COUNT(*) as clicks
FROM arb_visits
WHERE clicked == 1
GROUP BY country
ORDER BY clicks DESC"

其中給出以下 output:

[
  {
    "country": "United States",
    "clicks": 59,
    "id": null
  },
  {
    "country": "Canada",
    "clicks": 44,
    "id": null
  },
  {
    "country": "Germany",
    "clicks": 43,
    "id": null
  }
]

我怎樣才能將這兩個結合起來並得到一個 output 作為:

[
  {
    "country": "United States",
    "visits": 113,
    "clicks": 59
  },
  {
    "country": "Canada",
    "visits": 85,
    "clicks": 44
  },
  {
    "country": "Germany",
    "visits": 84,
    "clicks": 43
  }
]

在生產中,我使用 PostgreSQL,在開發中,我使用 SQLite。

我試過了,但沒有運氣。 我是 SQL 的新手。

使用countfilter

SELECT country, 
   count(*) as visits, 
   count(*) filter (where clicked = 1) as clicks 
FROM arb_visits 
GROUP BY country 
ORDER BY visits DESC;

如果您的 DBMS 不支持對聚合函數進行filter ,則

SELECT country, 
   count(*) as visits, 
   sum(case when clicked = 1 then 1 else 0 end) as clicks 
FROM arb_visits 
GROUP BY country 
ORDER BY visits DESC;

暫無
暫無

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

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