2016-11-10 4 views
-1

Я получил запрос, как это, его работы, как это должно работать, но я задаюсь вопросом, как сделать это в одном запросеИзменить Sub Query

SELECT 
(
Select count(exists) 
from country c 
    join special s ON c.id_special = s.id 
    join raports rap ON c.id = rap.id_raport 
where c.id_document = 7 and exists = 1 
and rap.id_data = 201501 and is_id = 1 
) as number_of_ID_in_table_exists, 
(
Select count(sps) 
from country c 
join special s ON c.id_special = s.id 
join raports rap ON c.id = rap.id_raport 
where c.id_document = 7 and sps = 1 
and rap.id_data = 201501 and is_id2 = 1 
) as number_of_ID2_in_table_exists; 
+1

См. Http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql- запрос – Strawberry

+0

Спасибо, у меня будет это в следующий раз. – Buckethead

ответ

1

Используйте case выражения сделать условный подсчет:

Select count(case when exists = 1 and is_id = 1 then 1 end) as number_of_ID_in_table_exists, 
     count(case when sps = 1 and is_id2 = 1 then 1 end) as number_of_ID2_in_table_exists 
from country c 
    join special s ON c.id_special = s.id 
    join raports rap ON c.id = rap.id_raport 
where rap.id_data = 201501 and c.id_document = 7 
+0

Он должен существовать = 1 вместо sps = 1 тоже, извините, мой плохой. Thx его работа, я люблю тебя :) Я попробовал его что-то вроде этого, но я болтаюсь: P – Buckethead

1
SELECT SUM(CASE WHEN is_id = 1 THEN 1 END) number_of_ID_in_table_exists 
     SUM(CASE WHEN is_id2 = 1 THEN 1 END) number_of_ID2_in_table_exists 
FROM country c 
JOIN special s ON c.id_special = s.id 
JOIN raports rap ON c.id = rap.id_raport 
WHERE c.id_document = 7 AND rap.id_data = 201501 AND [exists]= 1 
+0

Он должен существовать = 1 вместо sps = 1 тоже, извините, мой плохой, но его нормально – Buckethead