2016-02-12 90 views
2

我有3個查詢,但我想把它們合併成一個(有三列)。 this are my results結合列與不同的查詢sql

這是我的代碼:

Select family = count(s.destiny) from rental 
inner join cars as s on s.number_car = ID_car 
where s.destiny in (select destiny from cars where destiny like 'kids') 

Select lux = count(s.destiny) from rental 
inner join cars as s on s.number_car = ID_car 
where s.destiny in (select destiny from cars where destiny like 'luxury') 

Select sports = count(s.destiny) from rental 
inner join cars as s on s.number_car = ID_car 
where s.destiny in (select destiny from cars where destiny like 'sport car') 

你能幫我結合成一個 '選擇'?

+3

您所查詢的是怪異。 。 。爲什麼'.destiny在(選擇命運像「孩子」的汽車命運)而不是簡單地's.destiny ='kids''? –

回答

3

條件聚集看起來這正確做法:

Select sum(case when density = 'kids' then 1 else 0 end) as family, 
     sum(case when density = 'lux' then 1 else 0 end) as luxury, 
     sum(case when density = 'sport car' then 1 else 0 end) as sports  
from rental r inner join 
    cars s 
    on s.number_car = ID_car ; 
+0

這是最好的方法 – TheGameiswar

+1

是的,這個作品完美!謝謝 :) – Mao

0

簡單的答案是:

SELECT 
(
Select family = count(s.destiny) from rental 
inner join cars as s on s.number_car = ID_car 
where s.destiny in (select destiny from cars where destiny like 'kids') 
) as kids, 
(
Select lux = count(s.destiny) from rental 
inner join cars as s on s.number_car = ID_car 
where s.destiny in (select destiny from cars where destiny like 'luxury') 
) as luxury, 
(
Select sports = count(s.destiny) from rental 
inner join cars as s on s.number_car = ID_car 
where s.destiny in (select destiny from cars where destiny like 'sport car') 
) as sportsCar 

話雖這麼說,我強烈建議考慮在這裏卸下子查詢。

事情是這樣的:

SELECT destiny, COUNT(1) 
FROM cars 
GROUP BY destiny 
+0

謝謝!這是:) – Mao

+0

太棒了!請註冊並標記爲答案。您的代碼中的 – jhilden

0

爲什麼你不能嘗試呢?

Select destiny,count(*) from rental 
inner join cars as s on s.number_car = ID_car 
where s.destiny in ('cars','luxury') 
group by destiny 
+0

是bug:「',' 附近的語法不正確您不能在'汽車'和'豪華'之間輸入逗號。但感謝您的興趣:) – Mao

+0

根據戈登編輯 – TheGameiswar