[英]Oracle SQL combine 2 queries from same table with output in 2 different columns
我正在使用Oracle SQL數據庫。 我正在嘗試將這兩個查詢合並到同一張表中的一個查詢中:
select count(CustomerID) from Customers
where (City = 'Berlin' or City = 'London')
from Customers;
select count(CustomerID) from Customers
where (City = 'Mannheim' or City = 'Strasbourg')
from Customers;
我的輸出想像是在兩列上導出的:
| Berlin & London | Mannheim & Strasbourg |
|-----------------------------------------|
| 5 | 10 |
此處的db示例, https ://www.w3schools.com/sql/trysql.asp ? filename =trysql_op_in
我認為答案將是:
(select count(CustomerID) from Customers
where (City = 'Berlin' or City = 'London'))
union
(select count(CustomerID) from Customers
where (City = 'Marseille' or City = 'Tsawassen'));
union
(select count(CustomerID) from Customers
where (City = 'Strasbourg' or City = 'Madrid'));
仍在測試中...
最終通過使用這種情況完成了工作。 感謝所有參與的人!
SELECT
COUNT(CASE
WHEN work_zone = 'AMBGI01' OR
work_zone = 'AMBGI02' OR
work_zone = 'AMBGI03' AND
task_type = 'P' THEN work_zone
END) "HighBay Putaways",
COUNT(CASE
WHEN work_zone = 'AMBGI04' OR
work_zone = 'AMBGI05' OR
work_zone = 'AMBGI06' OR
work_zone = 'AMBGI07' AND
task_type = 'P' THEN work_zone
END) "LowBay Putaways",
COUNT(CASE
WHEN from_loc_id = 'THEWALL' AND
task_type = 'P' THEN from_loc_id
END) "THE WALL",
COUNT(CASE
WHEN tag_id like '%' AND
from_loc_id like 'EXPANS%' AND
task_type = 'P' THEN tag_id
END) "EXPANSION",
COUNT(CASE
WHEN final_loc_id like '_______' AND
(status = 'In Progress' OR
status = 'Released') AND
task_type = 'R' THEN final_loc_id
END) "Replens"
FROM move_task;
尚不清楚您有兩個表( customers
, country
)還是一個。 如果有兩個,則需要向我們展示結構。 w3schools.com說沒有像country
這樣的表格, customers
不包含store
欄。 無論如何,您都需要條件count
,如下所示:
select count(case when city in ('Berlin', 'London')
then 1 end) as "Berlin & London",
count(case when city in ('Mannheim', 'Strasbourg')
then 1 end) as "Mannheim & Strasbourg"
from Customers
where city in ('Berlin', 'London', 'Mannheim', 'Strasbourg')
您也可以使用pivot
,但這更簡單,更易讀,並且可以在較早的Oracle版本中使用。
最簡單的方法如下:
select count(CASE WHEN City = 'Berlin' or City = 'London' THEN City END) "Berlin & London"
, count(CASE WHEN City = 'Mannheim' or City = 'Strasbourg' THEN City END) "Mannheim & Strasbourg"
from Customers
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.