1

我有一个查询,我想最终将其放入视图中。

首先,只要我有 2 列,我可以以不同的方式命名我的 Flag 列吗?

另外,我可以在同一张表上使用不同的 WHERE 子句执行联合吗?

最后,将这 3 个选择放入 1 个视图的正确方法是什么?

    SELECT ID, 'Y' AS PW_CHANGE31, NULL AS LAST_LOGON90, NULL AS LAST_LOGON365 FROM user_info WITH (nolock) WHERE ([Last Password Change] < GETDATE() - 31)
UNION ALL
SELECT ID, NULL AS PW_CHANGE31, 'Y' AS LAST_LOGON90, NULL AS LAST_LOGON365 FROM user_info WITH (nolock) WHERE ([Last Logon] < GETDATE() - 90) AND ([Account Disabled] = 0)
UNION ALL
SELECT ID, NULL AS PW_CHANGE31, NULL AS LAST_LOGON90, 'Y' AS LAST_LOGON365 FROM user_info WITH (nolock) WHERE ([Last Logon] < GETDATE() - 365)

**更新为:

SELECT ID, '31' AS StatusVal FROM user_info WITH (nolock) WHERE ([Last Password Change] < GETDATE() - 31)
UNION 
SELECT ID, '90' AS StatusVal FROM user_info WITH (nolock) WHERE ([Last Logon] < GETDATE() - 90) AND ([Account Disabled] = 0)
UNION 
SELECT ID, '365' AS StatusVal FROM user_info WITH (nolock) WHERE ([Last Logon] < GETDATE() - 365)
4

2 回答 2

1

只要所有三列都类型兼容,这将起作用。该名称仅在结果列将被称为 PW_CHANGE31 时才重要,这最终可能会令人困惑。一般来说,我会给它起别名。

于 2013-11-08T21:04:24.967 回答
1

我刚刚意识到你在用这个查询做什么。我认为使用 UNION 方法而不是为同一个人设置 3 行(这是一个潜在的结果),您可能希望每个用户使用 1 行,并使用正确的值设置 3 个标志。注意:我没有运行此查询,可能存在语法错误。

SELECT u.ID,
    CASE WHEN ISNULL(u1.id) THEN 'N' ELSE 'Y' END CASE AS PW_CHANGE31,
    CASE WHEN ISNULL(u2.id) THEN 'N' ELSE 'Y' END CASE AS LAST_LOGON90,
    CASE WHEN ISNULL(u3.id) THEN 'N' ELSE 'Y' END CASE AS LAST_LOGON365
FROM user_info u
    LEFT OUTER JOIN user_info u1 on u.id = u1.id 
        AND ([Last Password Change] < GETDATE() - 31)
    LEFT OUTER JOIN user_info u2 on u.id = u2.id
        AND ([Last Logon] < GETDATE() - 90) AND ([Account Disabled] = 0)
    LEFT OUTER JOIN user_info u3 on u.id = u3.id
        AND ([Last Logon] < GETDATE() - 365)
WHERE u1.id IS NOT NULL
    OR u2.id IS NOT NULL
    OR u3.id IS NOT NULL

我试图在上面保留相同的三个子查询,以便您可以看到结构。我认为您应该完全消除连接,只需在 CASE 语句中进行算术运算,如下所示:

SELECT u.ID,
    CASE WHEN ([Last Password Change] < GETDATE() - 31) THEN 'Y' ELSE 'N' END CASE AS PW_CHANGE31,
    CASE WHEN (([Last Logon] < GETDATE() - 90) AND ([Account Disabled] = 0)) THEN 'Y' ELSE 'N' END CASE AS LAST_LOGON90,
    CASE WHEN ([Last Logon] < GETDATE() - 365) THEN 'Y' ELSE 'N' END CASE AS LAST_LOGON365
FROM user_info u
WHERE ([Last Password Change] < GETDATE() - 31)
    OR (([Last Logon] < GETDATE() - 90) AND ([Account Disabled] = 0))
    OR ([Last Logon] < GETDATE() - 365)

同样,这些查询可能存在语法错误,但我认为可以为您提供更好的查询性能以及每个用户只有一行且标志设置正确的事实。祝你好运!

于 2013-11-08T21:21:09.680 回答