【问题标题】:how do I write a select statement that will evaluate multiple fields to populate a new field value?如何编写将评估多个字段以填充新字段值的选择语句?
【发布时间】:2021-05-13 12:47:25
【问题描述】:

我一直在翻找一堆帖子,但没有找到适合我的问题的帖子。我尝试过 CASE 和 IIF,但似乎都不起作用。我妻子会说我不知道​​如何正确使用 Google。我将导出加载到 SQL Server Express 15 和 Access 16 (365) 中。我可以使用其中任何一个来实现我的目标。我有一个从数据导出中导入的表,其中包含以下字段:

LogonID
DeptName
CertDate
CertStatus
PastDue

我需要编写一个查询,该查询将提供具有适当值的状态字段,其中:

If ((CertDate Is Not Null) AND (CertStatus = ‘Current’) AND (PastDue = ‘No’)) then
    Status = ‘ReadOnTime’)

If ((CertDate Is Not Null) AND (CertStatus = ‘Current’) AND (PastDue = ‘Yes’)) then
    Status = ‘ReadLate’)

If ((CertDate Is Null) AND (CertStatus = ‘Pending’) AND (PastDue = ‘Yes’)) then
    Status = ‘UnReadLate’)

其他都是空白

【问题讨论】:

    标签: sql-server ms-access-2016


    【解决方案1】:

    在 SQL Server 中,您将使用 CASE 表达式。

    我使用了您示例中的字段名称,而您没有提供表名,因此您必须更新示例以满足您的需求。

    SELECT CASE WHEN [CertDate] IS NOT NULL
                     AND [CertStatus] = 'Current'
                     AND [PassDue] = 'No' THEN 'ReadOnTime'
                WHEN [CertDate] IS NOT NULL
                     AND [CertStatus] = 'Current'
                     AND [PassDue] = 'Yes' THEN 'ReadLate'
                WHEN [CertDate] IS NULL
                     AND [CertStatus] = 'Pending'
                     AND [PassDue] = 'Yes' THEN 'UnReadLate'
                ELSE ''
           END AS [Status]
    FROM   [YourTableName];
    

    【讨论】:

    • 很抱歉,我无法同时选择两者。 SQL 和 Access SQL 代码运行良好。谢谢你们。
    【解决方案2】:

    这是查询在 Access SQL 中的样子。

    Select
        LogonID, 
        DeptName, 
        CertDate, 
        CertStatus, 
        PastDue, 
        IIf (CertDate Is Not Null AND CertStatus = "Current" AND PastDue = "No", "ReadOnTime",
        IIf (CertDate Is Not Null AND CertStatus = "Current" AND PastDue = "Yes", "ReadLate",
        IIf (CertDate Is Null AND CertStatus = "Pending" AND PastDue = "Yes", "UnReadLate",
         ""))) As Status 
    From        Table
    

    【讨论】:

    • 很抱歉,我无法同时选择两者。 SQL 和 Access SQL 代码运行良好。谢谢你们。
    【解决方案3】:

    您尝试了哪些语法? 我会选择类似的东西

    update table my_table set
    Status = (case when condition1 then 'ReadOnTime' 
    else when condition2 then 'ReadLate' 
    else when condition2 then 'UnReadLate' 
    else '' end)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-21
      • 2023-03-11
      • 2017-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多