如何在子查询中使用两个where子句?

时间:2014-06-18 11:12:46

标签: sql sql-server

我需要查询一组数据(第一个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'
    )

5 个答案:

答案 0 :(得分:2)

您应该将where exists更改为and exists,这应该是它。

答案 1 :(得分: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')

答案 2 :(得分: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'
)

答案 3 :(得分: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'

答案 4 :(得分: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')