[英]SQL Select Subquery Count
這可能是一個簡單的 SQL 查詢,但我正在努力弄清楚如何做到這一點。
基本上我有兩個表(1. 客戶和 2. 響應)。 客戶表具有客戶是否處於活動狀態(是/否字段)。 響應表包含來自已發送調查的信息,其中一個字段是對員工尊重的響應的評級。
我的總體問題是,我希望通過尊重的回應來查看活躍客戶的數量,以及誰是活躍客戶以及他們尊重的回應評級。 output 是這樣的。 我希望 output 是三列。
因此,它將在第 1 列中列出 1-7,如果他們仍然是第 2 列中的客戶,則計算有多少客戶對每個評級做出響應,然后在第 3 列中計算他們的評級不是活躍客戶。
到目前為止,我的代碼錯誤說“用作表達式的子查詢返回了不止一行”,這是有道理的,因為將返回不止一行,我只是不確定在哪里解決這個問題。
任何指導表示贊賞,甚至鏈接到可能有助於我理解的信息。
我寫的代碼:
select respectful_responses,
(select count(respectful_responses)
from customer
inner join survey
on customer.cust_id = responses.cust_id
where active_cust = 'Yes'
group by respectful_responses) as "Lost Customers by Respectful Response",
(select count(respectful_responses)
from customer
inner join responses
on customer.cust_id = responses.cust_id
where active_cust = 'No'
group by respectful_responses) as "Active Customers by Respectful Response"
from customer
inner join survey_responses
on customer.cust_id = responses.cust_id
group by respectful_responses
order by respectful_responses;
您可以嘗試這樣的查詢:
SELECT s.respectful_responses
, count(*) FILTER (WHERE c.active_cust) AS "Active Customers by Respectful Response"
, count(*) FILTER (WHERE NOT c.active_cust) AS "Lost Customers by Respectful Response"
FROM customer AS c
INNER JOIN responses AS s
ON customer.cust_id = responses.cust_id
GROUP BY s.respectful_responses
ORDER BY s.respectful_responses
見手冊
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.