2012-05-17 87 views
1

仍嘗試習慣編寫查詢,並且遇到問題。涉及多個連接的子查詢

Select count(region) 
where (regionTable.A=1) in 
(
select jxn.id, count(jxn.id) as counts, regionTable.A 
from jxn inner join 
       V on jxn.id = V.id inner join 
       regionTable on v.regionID = regionTable.regionID 
group by jxn.id, regionTable.A 
) 

內部查詢給出了一個ID號在一列中,的時候,他們出現在表中的量,然後一點屬性,如果他們是在區域A的外部查詢工作,但我得到的錯誤是incorrect syntax near the keyword IN。內部查詢的,我想了許多有多少人是在區域A

+0

你能描述你想要的查詢返回什麼? –

+0

內部查詢給出了幾千個ID的列表,ID在表中的次數,以及它們是否在區域A中。有些是,(1),一些不是(0)。我希望我剛剛提到的查詢的一個子集只返回居住在區域A中的人員。我相信我現在已經向後查詢了我的查詢。 – wootscootinboogie

回答

0

你得到,因爲這一行的錯誤:

where (regionTable.A=1)

你不能在where in指定條件條款,只應列名

+0

當我得到錯誤:多部分標識符regionTable.A無法綁定。 – wootscootinboogie

+1

是的,您需要指定您在第一個查詢中選擇的內容。現在你從空中選擇。 –

+0

Facepalm。我想我倒退了。我想要的是大選擇查詢(其中regionA = 1)的一個子集。在這種情況下,我現在作爲外部查詢需要是內部的,正確的? – wootscootinboogie

1

您必須在查詢中指定表名前地方

Select count(region) 
    from table 
    where (regionTable.A=1) in 

而你必須選擇其中之一。

where regionTable.A = 1 

where regionTable.A in (..) 
0

像這樣的東西可能是你想要什麼:

SELECT COUNT(*) 
FROM 
    (
     select jxn.id, count(jxn.id) as counts, regionTable.A 
     from 
      jxn inner join 
      V on jxn.id = V.id inner join 
      regionTable on v.regionID = regionTable.regionID 
     group by jxn.id, regionTable.A 
    ) sq 
WHERE sq.a = 1 
1

您的查詢有幾個語法錯誤。根據您的意見,我認爲沒有必要爲一個子查詢,並希望此:

select jxn.id, count(jxn.id) as counts, regionTable.A 
from jxn inner join 
       V on jxn.id = V.id inner join 
       regionTable on v.regionID = regionTable.regionID 
where regionTable.A = 1 
group by jxn.id, regionTable.A 

可以進一步簡化爲:

select jxn.id, count(jxn.id) as counts 
    , 1 as A        --- you can even omit this line 
from jxn inner join 
       V on jxn.id = V.id inner join 
       regionTable on v.regionID = regionTable.regionID 
where regionTable.A = 1 
group by jxn.id 
+0

這是我在嘗試使用子查詢之前所做的。我試圖練習使用子查詢:) – wootscootinboogie