使用交叉连接格式化查询结果

时间:2015-04-14 16:29:19

标签: sql sql-server sql-server-2008

所以我仍然是新的交叉连接,我很少使用它们。我能够找到问题第一部分的答案,但不是第二部分。

我已经将结果输出到我想要的布局中,这里是结果

+-----------+-----------+-------------------------+
| Full Name | cert_type |       expiration        |
+-----------+-----------+-------------------------+
| Jane Doe  |         1 | 2015-09-26 00:00:00.000 |
| Jane Doe  |         2 | 2015-04-21 00:00:00.000 |
| Jane Doe  |         3 | 2015-12-16 00:00:00.000 |
| John Doe  |         1 | 2016-10-06 00:00:00.000 |
| John Doe  |         2 | 2015-04-19 00:00:00.000 |
| John Doe  |         3 | 2011-04-12 00:00:00.000 |
+-----------+-----------+-------------------------+

这也是我的查询:

SELECT
    [Full Name], 
    cert_type = X.which,
    expiration  =
        CASE X.which
        WHEN '1' THEN [License Exp Date]
        WHEN '2' THEN [Med Cert Exp Date]
        WHEN '3' THEN [Annual MVR Review Due]
        END
FROM employee_data.dbo.EmployeeDataBase
CROSS JOIN (SELECT '1' UNION ALL SELECT '2' UNION ALL SELECT '3') X (which)
WHERE [License Exp Date] BETWEEN GETDATE() AND DATEADD(dd, 7, GETDATE())
OR [Med Cert Exp Date] BETWEEN GETDATE() AND DATEADD(dd, 7, GETDATE())
OR [Annual MVR Review Due] BETWEEN GETDATE() AND DATEADD(dd, 7, GETDATE())
AND [Termination Date] IS NULL

正如您所看到的那样,即使WHERE子句仍然存在,它也会提取每个日期,并且我只想要WHERE子句中给定范围内的日期。我也是希望日期输出就像我将它们设置为一样 OUTPUT(VARCHAR(10), date, 101)

如果还有其他问题请告诉我,我会继续在这里工作。感谢您提供的所有帮助!

1 个答案:

答案 0 :(得分:1)

像这样的东西。你应养成使用datepart名称而不是缩写的习惯。它们很难记住,使用名称非常清楚。

with MyCTE as
(
    SELECT
        [Full Name], 
        cert_type = X.which,
        expiration  =
            CASE X.which
            WHEN '1' THEN [License Exp Date]
            WHEN '2' THEN [Med Cert Exp Date]
            WHEN '3' THEN [Annual MVR Review Due]
            END
    FROM employee_data.dbo.EmployeeDataBase
    CROSS JOIN (SELECT '1' UNION ALL SELECT '2' UNION ALL SELECT '3') X (which)
    WHERE [License Exp Date] BETWEEN GETDATE() AND DATEADD(dd, 7, GETDATE())
    OR [Med Cert Exp Date] BETWEEN GETDATE() AND DATEADD(dd, 7, GETDATE())
    OR [Annual MVR Review Due] BETWEEN GETDATE() AND DATEADD(dd, 7, GETDATE())
    AND [Termination Date] IS NULL
)

select *
from MyCTE
where expiration BETWEEN GETDATE() AND DATEADD(DAY, 7, GETDATE())