2014-06-18 94 views
0

我需要查詢一組數據(第一個WHERE)並基於該結果的子查詢與另一個WHERE。使用下面的代碼 我得到如何在子查詢中使用兩個where子句?

**Incorrect syntax near the keyword 'where'.** 

你能告訴我我在做什麼錯在這裏?


select * from [Analytics] 
    WHERE 
    DateCreated >= '2014-05-01' 
    AND DateCreated < '2014-06-01' 
    AND Identification = 'ElementFlow' 
    where exists 
    (
    SELECT * 
    FROM [Analytics] 
    WHERE Location = 'x.DetailsAdvertisement' 
    OR Location = 'x.DetailsShop' 
    OR Location = 'x.None' 
    OR Location = 'x' 
    ) 
+1

您是來自同一個表中選擇。那麼爲什麼你需要一個子查詢? –

+2

用'和'替換第二個'where'。 –

+1

只是一句話:一旦你用AND替換第二個WHERE,那麼exists子句是正確的。如果您在子查詢中查找的數據存在,它將選擇**所有**指定記錄,否則將選擇** none **。這是因爲子查詢與主查詢中的記錄沒有關係。這是需要的嗎? –

回答

2

你應該改變where existsand exists這應該是它。

0

您正在使用WHERE子句兩次。用AND替換第二個WHERE,它應該可以工作。

select * from [Analytics] 
WHERE 
DateCreated >= '2014-05-01' 
AND DateCreated < '2014-06-01' 
AND Identification = 'ElementFlow' 
AND exists 
(
SELECT * 
FROM [Analytics] 
WHERE Location = 'x.DetailsAdvertisement' 
OR Location = 'x.DetailsShop' 
OR Location = 'x.None' 
OR Location = 'x' 
) 
1

通過移除試試這個where子句來兩次

select * from [Analytics] 
    WHERE 
    DateCreated >= '2014-05-01' 
    AND DateCreated < '2014-06-01' 
    AND Identification = 'ElementFlow' 
    AND exists 
    (
    SELECT * 
    FROM [Analytics] 
    WHERE Location = 'x.DetailsAdvertisement' 
    OR Location = 'x.DetailsShop' 
    OR Location = 'x.None' 
    OR Location = 'x' 
    ) 

或者你試試這個...

select * from [Analytics] 
     WHERE 
     DateCreated >= '2014-05-01' 
     AND DateCreated < '2014-06-01' 
     AND Identification = 'ElementFlow' 
     AND location in ('x.DetailsAdvertisement' ,'x.DetailsShop','x.None','x') 
0

使用一個以上的水平,它是怎樣的聲音?

SELECT * FROM 
(
    select * from [Analytics] 
    where exists 
    (
    SELECT * 
    FROM [Analytics] 
    WHERE Location = 'x.DetailsAdvertisement' 
    OR Location = 'x.DetailsShop' 
    OR Location = 'x.None' 
    OR Location = 'x' 
    ) 
) a 
WHERE 
    DateCreated >= '2014-05-01' 
    AND DateCreated < '2014-06-01' 
    AND Identification = 'ElementFlow' 
0

試試這個:

SELECT * 
FROM [Analytics] 
WHERE DateCreated >= '2014-05-01' AND DateCreated < '2014-06-01' 
     AND Identification = 'ElementFlow' 
     AND Location IN('x.DetailsAdvertisement', 'x.DetailsShop', 'x.None', 'x')