比较子查询的值

时间:2015-12-17 14:18:29

标签: sql sql-server tsql

我在存储过程中有以下SQL需要更新:

SELECT MEM.Id,
    EN.artistName,
    EN.dateAdded,
    EN.voteStatus,
    ES.enterNextRound,
    ES.notified,
    ES.voted,
    GR.genre,
    ES.entrantId AS bandID,
    ES.rnd2Feedback AS feedback,
    ES.compositionVote,
    ES.vocalsVote,
    ES.originalityVote,
    (SELECT COUNT(Voted)
    FROM recEntrantStatus
    WHERE voted = 1
      AND roundId = 2
      AND entrantId = ES.entrantId) CountVoted,
    (SELECT COUNT(Voted)
    FROM recEntrantStatus
    WHERE roundId = 2
      AND entrantId = ES.entrantId) CountTotalVotes,
    (SELECT COUNT(Id)
    FROM recMembers) TotalJudges
    FROM recMembers AS MEM
    LEFT JOIN recEntrantStatus AS ES
       ON MEM.Id = ES.judgeId
    LEFT JOIN recEntrants AS EN
       ON ES.entrantId = EN.Id
    LEFT JOIN recGenre AS GR
       ON EN.genreId = GR.Id
    WHERE MEM.Id = @memberId
       AND ES.roundId = 2
    ORDER BY bandID DESC

这可以显示所有匹配的记录,但是我现在需要返回CountVoted的值小于CountTotalVotes的记录。

我尝试在WHERE子句中添加一个简单的compatison,例如:

AND CountVoted< CountTotalVotes

我也尝试过:

AND recEntrantStatus.CountVoted< recEntrantStatus.CountTotalVotes

CountVoted.CountVoted< CountTotalVotes.CountTotalVotes

但是这两个字段被归类为模糊或不存在的结果相同。那么为了能够进行比较,我该如何调整事物呢?

1 个答案:

答案 0 :(得分:3)

最简单的方法是将整个查询抛出到子查询中:

where

修改

我将列名更改为您的查询中的内容以及您在说明中提到的内容,而不是您尝试ORDER BY条件中的内容。

进一步修改

您应该将order by子句替换为外部查询..

修改编辑

注意到您没有选择在lubridate中使用的属性,添加到选择中,或选择其他属性进行订购