0

我有一个简单的查询,我想要一些具体的结果,但不确定正确的方法。我正在使用 SQL Server 数据库,我的查询如下:

SELECT  dt.year ,
        db.dist_code ,
        db.dist_name ,
        db.s_code ,
        db.s_name ,
        fl.zip ,
        fl.num_births ,

        total_enrollment 
FROM    dbo.fact_enrollment_school AS fs
        INNER JOIN dbo.dim_building AS db ON fs.building_key = db.building_key
        INNER JOIN dbo.dim_time AS dt ON fs.time_key = dt.time_key
        LEFT OUTER JOIN dbo.fact_live_birth AS fl ON dt.time_key = fl.time_key
                                                AND db.building_key = fl.building_key

GROUP BY dt.year ,
        db.dist_code ,
        db.dist_name ,
        db.school_code ,
        db.school_name ,
        fl.zip ,
        total_enrollment ,
        fl.num_births

在此处输入图像描述

我需要的是为每个相同的 District_code 输出 num_births 总数。

期望的输出:

在此处输入图像描述

4

1 回答 1

2

我认为您可以通过窗口功能来实现这一点:

SELECT  dt.year ,
    db.dist_code ,
    db.dist_name ,
    db.s_code ,
    db.s_name ,
    fl.zip ,
    sum(fl.num_births) over (partition by dt.year, db.dist_code),

    total_enrollment 
FROM    dbo.fact_enrollment_school AS fs
    INNER JOIN dbo.dim_building AS db ON fs.building_key = db.building_key
    INNER JOIN dbo.dim_time AS dt ON fs.time_key = dt.time_key
    LEFT OUTER JOIN dbo.fact_live_birth AS fl ON dt.time_key = fl.time_key
                                            AND db.building_key = fl.building_key;
于 2013-05-30T21:02:59.910 回答