2016-11-10 31 views
-1

我得到了這樣的查詢,其作爲它的工作應該工作,但我不知道如何在一個查詢使其更改子查詢

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