Sql server多条件子查询

时间:2013-08-24 13:27:14

标签: sql sql-server tsql correlated-subquery

我尝试在子查询中使用复合条件,但它没有返回预期的结果。您可以查看下面的示例,看看查询无法解决的原因吗?

Table : 1
EntityID   StartDate    EndDate

121        2013-08-01   2013-08-31
122        2013-08-01   2013-08-31
123        2013-08-01   2013-08-31


Table : 2
EntityID     AttributeID    AttributeValue

121            41                 304
122            41                 304
123            41                 304
123            54                 307    

现在我正在尝试基于TableID 2中的AttributeID和AttribueValue以及Stardate来获取,并使用以下查询从table1结束。 (例如:41和304以及54和307满足于123只我想要获取123只有一条记录)

SELECT pe.EntityID
FROM  table1 pe          
WHERE  pe.StartDate = '2013-08-01'
       AND pe.EndDate = '2013-08-31'
       AND pe.EntityID IN (SELECT peaiv.EntityID
                     FROM   table2 peaiv
                     WHERE  peaiv.AttributeID IN (41)
                            AND peaiv.[Value] IN (304)
                            AND peaiv.EntityID IN (SELECT peaiv.EntityID
                                                   FROM   
                                                          PT_EntityAttributesIntValues 
                                                          peaiv
                                                   WHERE  peaiv.AttributeID IN (54)
                                                          AND peaiv.[Value] IN (307))


EntitID
--------
121
122
123

查询返回上述结果,但我期待结果只有 123 。任何人都可以尝试这个。

2 个答案:

答案 0 :(得分:3)

Declare @Table1 table(EntityID int,  StartDate datetime,    EndDate datetime)
Insert into @Table1
SELECT 121,'2013-08-01','2013-08-31'
UNION SELECT 122,'2013-08-01','2013-08-31'
UNION SELECT 123,'2013-08-01','2013-08-31'

Declare @Table2 Table (EntityID int, AttributeID int , AttributeValue int)
Insert into @Table2
SELECT 121,41,304
UNION SELECT 122,41,304
UNION SELECT 123,41,304
UNION SELECT 123,54,307

SELECT EntityID FROM @Table1 pe
WHERE
pe.StartDate = '2013-08-01' AND pe.EndDate = '2013-08-31'
AND EntityID in
(SELECT EntityID from @Table2
WHERE (AttributeID=41 and AttributeValue=304)
)
AND EntityID in
(SELECT EntityID from @Table2
WHERE (AttributeID=54 and AttributeValue=307)
)

答案 1 :(得分:2)

我会将此作为“set-within-sets”查询,然后再加入表1以填写这些详细信息:

select t1.*
from table1 t1 join
     (select EntityId
      from table2 t2
      group by EntityId
      having sum(case when AttributeId = 41 and AttributeValue = 304 then 1 else 0 end) > 0 and
             sum(case when AttributeId = 54 and AttributeValue = 307 then 1 else 0 end) > 0
     ) t2
     on t1.EntityId = t2.EntityId;

having子句中的每个条件都在测试匹配和实体的行集中的一对值。这样可以轻松添加其他条件。