组合两个具有不同行大小的SQL查询

时间:2013-07-03 18:32:31

标签: sql sql-server-2008

我有以下问题:

SELECT TOP 10 
    EnrolledDate,
    DATEDIFF(MINUTE, EnrolledTimeUtc, EnrollmentCompleteTimeUtc) as Enroll
FROM StudentEnrollment
WHERE EnrolledTimeUtc IS NOT NULL


SELECT
    AVG(DATEDIFF(MINUTE, EnrolledTimeUtc, EnrollmentCompleteTimeUtc)) as AvgEnrollmentTime,
    STDEV(DATEDIFF(MINUTE, EnrolledTimeUtc, EnrollmentCompleteTimeUtc)) as  EnrollmentStDev 
FROM StudentEnrollment
WHERE EnrolledTimeUtc IS NOT NULL

我正在尝试组合这些查询,以便我可以在一个表中查看数据。有可能吗?

我尝试使用

组合它们
SELECT (SELECT... ), (SELECT...)

但是因为与上述脚本不匹配的行数不起作用。

第一个查询返回如下内容:

EnrolledDate                Enroll
2013-04-24 23:17:59.613     1
2013-04-24 23:18:01.753     5
2013-04-24 23:18:03.517     10
2013-04-24 23:18:05.703     8

第二个查询返回:

AvgEnrollmentTime EnrollmentStDev
19                22.1125   

我希望将这两个表组合在一起,因此它应该显示为:

EnrolledDate                Enroll       AvgEnrollmentTime EnrollmentStDev
2013-04-24 23:17:59.613     1            19                22.1125
2013-04-24 23:18:01.753     5
2013-04-24 23:18:03.517     10
2013-04-24 23:18:05.703     8

在使用Hiren的脚本后,我可以这样工作:

EnrolledDate                Enroll       AvgEnrollmentTime EnrollmentStDev
2013-04-24 23:17:59.613     1            19                22.1125
2013-04-24 23:18:01.753     5            Null              Null
2013-04-24 23:18:03.517     10           Null              Null
2013-04-24 23:18:05.703     8            Null              Null 

但有可能让它看起来像这样吗?

EnrolledDate                Enroll       AvgEnrollmentTime EnrollmentStDev
2013-04-24 23:17:59.613     1            19                22.1125
2013-04-24 23:18:01.753     5            19                22.1125
2013-04-24 23:18:03.517     10           19                22.1125
2013-04-24 23:18:05.703     8            19                22.1125

1 个答案:

答案 0 :(得分:0)

很容易做到。你必须使用全外连接,并使用行号连接两个表。 您可以执行以下查询:

SELECT A.EnrolledDate , A.Enroll ,B.AvgEnrollmentTime , B.EnrollmentStDev
FROM
(
    SELECT TOP 10
    EnrolledDate,
    DATEDIFF(MINUTE, EnrolledTimeUtc, EnrollmentCompleteTimeUtc) as Enroll
    FROM StudentEnrollment
    WHERE EnrolledTimeUtc IS NOT NULL
) AS A
,
(
    SELECT
    AVG(DATEDIFF(MINUTE, EnrolledTimeUtc, EnrollmentCompleteTimeUtc)) as AvgEnrollmentTime,
    STDEV(DATEDIFF(MINUTE, EnrolledTimeUtc, EnrollmentCompleteTimeUtc)) as  EnrollmentStDev 
    FROM StudentEnrollment
    WHERE EnrolledTimeUtc IS NOT NULL
) AS B