【问题标题】:SQL return 1 in case switch when count is bigger than 0当 count 大于 0 时 SQL 返回 1 以防切换
【发布时间】:2022-01-14 01:26:04
【问题描述】:

我在存储过程中有一个 int 的输入列表,每个 id 都有一个文档,每个文档都有多个子文档。连接到subdocument.DocumentId = document.DocumentId

我要做的是返回一个对象列表 (document.DocumentId int, IsValid bool)。

如果每个连接的子文档的 2 列不为空,则布尔值为真。

PARAMLIST:ID 列表

SELECT 
    IDS.ParamList AS documentId,
    CASE 
        WHEN (SELECT COUNT(*) 
              FROM Document D
              JOIN SubDocument SD ON SD.DocumentId = D.DocumentId
              WHERE SD.DocumentId = IDS.ParamList 
                AND SD.PaymentDate IS NULL 
                AND SD.ConnectionContractIsAcceptedDate IS NULL) > 0
             THEN 1
             ELSE 0 
    END AS IsValid
FROM 
    @documentIds IDS

如您所见,我的逻辑是进行大小写切换,我计算每个 SubDocument 至少没有填充一列,但查询只返回 2 个列名

文档表:

DocumentId CreatedBy
1 John
2 Jill

子文档表:

SubDocumentId DocumentId Field1 Field2
3 1 NULL 2010-02-02
4 2 2021-01-01 2018-03-03
5 1 2020-10-10 2015-11-15
6 2 2019-10-01 2013-12-12

这里的预期结果是:

DocumentId IsValid
1 false
2 true

【问题讨论】:

  • 为什么SELECT COUNT(*) 为什么不只是CASE WHEN EXISTS

标签: sql sql-server stored-procedures


【解决方案1】:

您可以将表变量连接到表中。
然后使用条件聚合计算IsValid。

declare @DocumentIds table (
 DocumentId int
);

insert into @DocumentIds values (1),(2);

SELECT Doc.DocumentId, Doc.CreatedBy
, CAST(MIN(
      CASE
      WHEN (SubDoc.Field1 IS NULL OR SubDoc.Field2 IS NULL) 
      THEN 0
      ELSE 1
      END) AS BIT) AS IsValid
FROM Document Doc
JOIN @DocumentIds Ids 
  ON Ids.DocumentId = Doc.DocumentId
LEFT JOIN SubDocument SubDoc
  ON SubDoc.DocumentId = Doc.DocumentId
GROUP BY Doc.DocumentId, Doc.CreatedBy
ORDER BY Doc.DocumentId;
DocumentId CreatedBy IsValid
1 John False
2 Jill True

dbfiddle here

上的演示

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 2016-03-11
    • 2021-05-15
    • 2016-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多