TSQL - TOP和COUNT在一个SELECT中

时间:2013-04-17 12:14:02

标签: sql tsql

我尝试将这两个语句合并为一个,但我的所有尝试都失败了! 是否可以合并它们?

-- Is there a open answer?
SELECT CASE COUNT(tbl_Communication.pk_Communication) WHEN 0 
       THEN 0 ELSE 1 END AS hasAnsweredCom
FROM   tbl_Communication 
JOIN   tbl_CommunicationElements ON tbl_CommunicationElements.pk_Communication = tbl_Communication.pk_Communication
WHERE  tbl_Communication.pk_Ticket = @pk_Ticket
  AND tbl_Communication.isClosed = 0 
  AND tbl_Communication.pk_CommunicationType = (SELECT pk_CommunicationType
                                                FROM   tbl_CommunicationType
                                                WHERE  name = 'query')

-- Get the answer text
SELECT TOP 1 tbl_Communication.subject AS hasAnsweredComStepName
FROM   tbl_Communication 
JOIN   tbl_CommunicationElements ON tbl_CommunicationElements.pk_Communication = tbl_Communication.pk_Communication
WHERE  tbl_Communication.pk_Ticket = @pk_Ticket 
  AND tbl_Communication.isClosed = 0 
  AND tbl_Communication.pk_CommunicationType = (SELECT pk_CommunicationType
                                                FROM   tbl_CommunicationType
                                                WHERE  name = 'query')
ORDER BY tbl_Communication.pk_Communication

2 个答案:

答案 0 :(得分:1)

右连接技巧。

SELECT TOP 1
    CASE WHEN tbl_CommunicationElements.pk_Communication IS NULL THEN 0 ELSE 1 END hasAnsweredCom
    , tbl_Communication.subject AS hasAnsweredComStepName
FROM   tbl_Communication 
JOIN   tbl_CommunicationElements ON tbl_CommunicationElements.pk_Communication = tbl_Communication.pk_Communication
RIGHT JOIN (VALUES(1)) AS Ext(x) ON (
  tbl_Communication.pk_Ticket = @pk_Ticket 
  AND tbl_Communication.isClosed = 0 
  AND tbl_Communication.pk_CommunicationType = (SELECT pk_CommunicationType
                                                FROM   tbl_CommunicationType
                                                WHERE  name = 'query')
)

答案 1 :(得分:1)

如果您愿意将两个结果放在一行,则以下工作:

select (CASE count(*) WHEN 0 THEN 0 ELSE 1 END) AS hasAnsweredCom,
       MAX(case when seqnum = 1 then subject end) as hasAnsweredComStepName
from (SELECT tbl_Communication.pk_Communication, tbl_Communication.subject,
             ROW_NUMBER() over (order by pk_communication) as seqnum                               
      FROM   tbl_Communication 
      JOIN   tbl_CommunicationElements ON tbl_CommunicationElements.pk_Communication = tbl_Communication.pk_Communication
      WHERE  tbl_Communication.pk_Ticket = @pk_Ticket
        AND tbl_Communication.isClosed = 0 
        AND tbl_Communication.pk_CommunicationType = (SELECT pk_CommunicationType
                                                      FROM   tbl_CommunicationType
                                                      WHERE  name = 'query')
     ) t

如果没有答案,第二个值将为NULL。

至于返回两行。我的猜测是subject是一个字符串而hasAnsweredCom是一个整数。类型冲突,因此任何类型的union或将结果放在一起可能会导致第二行出现类型冲突。