一尘不染

SQL Server-按所有组返回的记录数进行汇总

sql

假设我的SQL Server 2012数据库中有下表:

MyTable:

DateCol       FkId    Sector      Value
--------------------------------------------
2018-01-01     1        A            1
2018-01-02     1        A            2
2018-01-03     1        A            3
2018-01-04     1        A            4
2018-01-01     1        B            1
2018-01-04     1        B            4
2018-01-01     1        C            1
2018-01-03     1        C            3
2018-01-04     1        C            4
2018-01-01     2        A            1
...

我想获取特定扇区的每个扇区的平均值FkId但要基于FkId的总数中可用的日期总数 。也就是说,如果我想获得的平均FkId=
1的日期,也就是说,2018-01-012018-01-10我的结果集将是:

Sector       AvgVal
---------------------------------
A            (1+2+3+4) / 4 = 2.5
B            (1+4) / 4 = 1.25
C            (1+3+4) / 4 = 2

换句话说,不除以该部门可用的日期数,而是除以该表中该日期范围的日期总数FkId

我认为可以通过以下方式对CTE进行此操作:

DECLARE @FkId INT = 1,
        @StartDate DATE = '2018-01-01',
        @EndDate DATE = '2018-01-10'

DECLARE @MyTable TABLE
                 (
                     DateCol DATE,
                     FkId INT,
                     Sector VARCHAR(1),
                     Value FLOAT
                 );

INSERT INTO @MyTable (DateCol, FkId, Sector, Value)
VALUES
    ('2018-01-01', 1, 'A', 1),
    ('2018-01-02', 1, 'A', 2),
    ('2018-01-03', 1, 'A', 3),
    ('2018-01-04', 1, 'A', 4),

    ('2018-01-01', 1, 'B', 1),
    ('2018-01-04', 1, 'B', 4),

    ('2018-01-01', 1, 'C', 1),
    ('2018-01-03', 1, 'C', 3),
    ('2018-01-04', 1, 'C', 4),

    ('2018-01-01', 2, 'A', 1);

WITH NumDates AS
(
    SELECT
        Sector,
        COUNT(DateCol) AS cnt
    FROM
        @MyTable
    WHERE
        DateCol BETWEEN @StartDate AND @EndDate
        AND FkId = @FkId
    GROUP BY
        Sector
),
MaxNumDates AS
(
    SELECT
        MAX(cnt) AS MaxNum
    FROM
        NumDates
)
SELECT
    Sector,
    SUM(Value) / MaxNum AS AvgVal
FROM
    @MyTable
JOIN 
    MaxNumDates ON 1 = 1
WHERE
    DateCol BETWEEN @StartDate AND @EndDate
    AND FkId = @FkId
GROUP BY
    Sector, MaxNum

但我真的希望有更好的方法。有什么想法吗?


阅读 150

收藏
2021-03-08

共1个答案

一尘不染

试试这个:

select dateCol,
       fkid, 
       sector,
       sum(value) over (partition by fkid, sector) /
       (select count(distinct dateCol) from @MyTable where fkid = t.fkid)
from @MyTable t

或者

select fkid, 
       sector,
       sum(value) /
       (select count(distinct dateCol) from @MyTable where fkid = t.fkid)
from @MyTable t
group by fkid, sector
2021-03-08