0

我尝试在子查询中使用复合条件,但它没有返回预期的结果。你能看看下面的例子,看看为什么查询不成功吗?

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    

现在,我正在尝试使用以下查询根据 Table-2 中的 AttributeID 和 AttribueValue 以及 table1 中的 Stardate 和 enddate 获取。(例如: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。任何人都可以尝试这个。

4

2 回答 2

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)
)
于 2013-08-24T14:29:30.720 回答
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测试与实体匹配的行集中的一对值。这使得添加附加条件变得容易。

于 2013-08-24T14:54:32.743 回答