计数和划分子查询:SQL 服务器

Count and divide subquery: SQL Server

这是一个 table 我正在阅读:

sk_calendar_week  | ClientId  | Amount 
------------------+-----------+-------
2014001           | 1         | 550
2014002           | 2         | 900
2014003           | 3         | 389
2014004           | 4         | 300

这是我正在使用的查询:

declare @IniDate as int = 20140610, @EndDate as int = 20150425

select   
    COUNT(distinct sk_calendar_week) WeekQ, 
    COUNT(distinct sk_calendar_Month) MonthQ
from
    (select   
         sk_date, sk_calendar_week, sk_calendar_Month, 
         ClientId, Amount
     from 
         TableA
     where 
         Sk_Date between @IniDate and @EndDate) q1

这个查询 returns:

WeekQ | MonthQ
------+-------
4     | 1

如何将 WeekQ 的 4 除以 Amount (550/4; 900/4; 389/4...),以获得这样的结果?

sk_calendar_week   | ClientId | Amount | Division
-------------------+----------+--------+---------
2014001            | 1        | 550    | 137.5
2014002            | 2        | 900    | 225
2014003            | 3        | 389    | 97.25
2014004            | 4        | 300    | 75

尝试使用 window 函数:

declare @IniDate as int = 20140610, @EndDate as int = 20150425

select *, amount*1.0/count(*) over() as division
from(
    select   sk_date
            ,sk_calendar_week
            ,sk_calendar_Month
            ,ClientId
            ,Amount
    from TableA
    where Sk_Date between @IniDate and @EndDate
)q1

您可以使用第一个查询来填充局部变量,然后像这样在第二个查询中使用它:

declare @IniDate as int = 20140610, 
              @EndDate as int = 20150425,
              @Week int

select @Week = COUNT(distinct sk_calendar_week) 
from TableA where Sk_Date between @IniDate and @EndDate )

Select sk_calendar_week,
            ClientId,
            Amount,
            cast(Amount as decimal(8,2)) / @Week as Divsion

子查询版本会受到性能影响,但这里有一个例子:

Select sk_calendar_week,
            ClientId,
            Amount,
            cast(Amount as decimal(8,2)) / 
            (select COUNT(distinct sk_calendar_week) 
             from TableA where Sk_Date between @IniDate and @EndDate ) as Divsion