sql-server 合并SQL Server IIF函数和Count函数

insrf1ej  于 2022-10-31  发布在  SQL Server
关注(0)|答案(2)|浏览(217)

我开发了一个电子邮件服务,有一个表格,必须显示所有电子邮件有关的一个人在一个网格。
我使用SQL查询来显示如下结果:

SELECT
    FOLDERNAME,
    MAILFROM,
    MAILTO,
    LEFT(SUBJ, 200) + IIF(LEN(SUBJECT) > 200, '...', '')
        AS 'Subject',
    CAST(CNT AS VARCHAR(300)) + IIF(LEN(CNT) > 300, '...', '')
        AS 'Content',
    STUFF(STUFF(STUFF(STUFF(MAILTIMESTAMP, 5, 0, '-'), 8, 0, '-'), 11, 0, ' '), 14, 0, ':')
        AS 'Date - Time',
    (SELECT COUNT(*) FROM ATTACHMENTS WHERE MESSAGEID = MESSAGES.MESSAGEID)
        AS Attachments
FROM
    MESSAGES, FOLDERS
WHERE
    FOLDERS.FOLDERID = MESSAGES.FOLDERID AND
    MESSAGES.PKEY = '4070486';

PKEY是个人关键字,Attachments是数据库中以BLOB形式存在的附件数。
问题是我无法在内部Select语句中合并IIF函数和Count函数来显示附件,如下所示:

SELECT IIF(COUNT(*) > 1, 'Yes', 'No')
FROM ATTACHMENTS WHERE MESSAGEID = MESSAGES.MESSAGEID

请注意,每封电子邮件都有一个XML附件,如果有多个附件,则应写为“是”,否则为“否”。
我试过其他的方法,比如WHERE EXISTS或者IIF((SELECT...)〉1,...),都没有成功。
我认为应该有一个更好的解决办法。

0sgqnhkj

0sgqnhkj1#

您是否尝试过将IIF(...)替换为如下CASE语句?

SELECT
    CASE
        WHEN COUNT(*) <= 1 THEN 'No'
        ELSE 'Yes'
    END AS HAVE_MULTIPLE_VALUES
FROM ATTACHMENTS
WHERE MESSAGEID = MESSAGES.MESSAGEID
fykwrbwg

fykwrbwg2#

SELECT
    FOLDERNAME,
    MAILFROM,
    MAILTO,
    LEFT(SUBJ, 200) + IIF(LEN(SUBJECT) > 200, '...', '')
        AS 'Subject',
    CAST(CNT AS VARCHAR(300)) + IIF(LEN(CNT) > 300, '...', '')
        AS 'Content',
    STUFF(STUFF(STUFF(STUFF(MAILTIMESTAMP, 5, 0, '-'), 8, 0, '-'), 11, 0, ' '), 14, 0, ':')
        AS 'Date - Time',
    ATT.N AS Attachments
FROM
    MESSAGES, FOLDERS
LEFT JOIN (SELECT MESSAGEID, COUNT(*) as N FROM ATTACHMENTS GROUP BY MESSAGEID) ATT on ATT.MESSAGEID = MESSAGES.MESSAGEID    
WHERE
    FOLDERS.FOLDERID = MESSAGES.FOLDERID AND
    MESSAGES.PKEY = '4070486';

相关问题