ms sql和distinct和结果集不是预期的

时间:2019-05-31 17:15:58

标签: sql sql-server

我试图让我的查询不返回任何结果,如果一列的所有行的内容都超过一个CONTENT_STATUS。有两个状态显示-已删除和当前状态,因此我希望计数显示为2,而不是1。然后,group by应该看到有2个状态,并且不显示任何行。这可能很简单,但是我很难解决这个问题,所以我正在寻求您的帮助。

enter image description here

SELECT CONTENT.CONTENTID, sub.TITLE, sub.PAGEID, sub.SPACEID, 
sub.CONTENT_STATUS, sub.VERSION
FROM CONTENT, (
    SELECT TITLE, PAGEID, SPACEID, CONTENT_STATUS, VERSION
    FROM CONTENT 
    where CONTENTTYPE = 'ATTACHMENT' AND TITLE = 
'RWE_SMART_Optimisation-SAS Phase 2 Plan_v1.mpp'
    GROUP BY TITLE, PAGEID, SPACEID, CONTENT_STATUS, VERSION
    ) sub
WHERE 
sub.TITLE = CONTENT.TITLE AND
sub.PAGEID = CONTENT.PAGEID AND
sub.SPACEID = CONTENT.SPACEID AND
sub.CONTENT_STATUS = CONTENT.CONTENT_STATUS AND
sub.VERSION = CONTENT.VERSION
GROUP BY CONTENTID,sub.TITLE, sub.PAGEID, sub.SPACEID, 
sub.CONTENT_STATUS, sub.VERSION 
HAVING count(distinct sub.CONTENT_STATUS) = 1
ORDER BY TITLE, SPACEID

数据:     CONTENTID标题PAGEID空间ID CONTENT_STATUS版本

28213489    RWE_SMART_Optimisation-SAS Phase 2 Plan_v1.mpp  9044469 9371651  current    1
106102818   RWE_SMART_Optimisation-SAS Phase 2 Plan_v1.mpp  9044469 9371651 current 1
28213490    RWE_SMART_Optimisation-SAS Phase 2 Plan_v1.mpp  9044469 9371651 current 2
22118420    RWE_SMART_Optimisation-SAS Phase 2 Plan_v1.mpp  9044469 9371651  deleted    2

0 个答案:

没有答案