3

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

-- 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
4

2 回答 2

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')
)
于 2013-04-17T12:21:53.430 回答
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结果或将结果组合在一起都可能导致第二行出现类型冲突。

于 2013-04-17T13:14:49.477 回答