只要列数相同,联盟可以有另一个列名吗?

时间:2013-11-08 20:58:58

标签: sql sql-server union

我有一个想要最终放入视图的查询。

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

另外,我可以在同一个表上使用不同的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)

2 个答案:

答案 0 :(得分:1)

只要所有三列都是类型兼容的,这将有效。该名称仅在结果列被称为PW_CHANGE31时才有意义,这可能最终会引起混淆。一般来说,我是别名。

答案 1 :(得分: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)

同样,这些查询可能会出现语法错误,但我认为这会让您获得性能更好的查询以及每个用户只有一行并且标记设置正确的事实。祝你好运!