【问题标题】:Count and divide subquery: SQL Server数除子查询:SQL Server
【发布时间】:2015-07-07 17:46:58
【问题描述】:

这是我正在阅读的表格:

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

此查询返回:

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

如何将WeekQ 中的 4 除以金额(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

【问题讨论】:

  • sk_date 来自哪里?它是否也存储为int
  • @MartinSmith 是的,错字,我已经修复了
  • @APH 是的,sk_date 来自同一张表,是一个int。

标签: sql-server count subquery division


【解决方案1】:

您可以使用您的第一个查询来填充一个局部变量,并在第二个查询中使用它,如下所示:

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

【讨论】:

  • 如果我不想使用变量,我该怎么做?
  • 您可以使用子查询或 cte。
  • 你能帮我做一个子查询吗?我对 sql 有点陌生,或者我在哪里可以看到它的例子?
【解决方案2】:

试试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

【讨论】:

  • 与除以COUNT(distinct sk_calendar_week) 不同,除非它既是唯一的又不是空的。
  • @MartinSmith,当然。我只是没有看到任何有问题的重复项和空值。
  • 问题中缺少很多细节,事实上存在一个名为sk_date 的列并且他们发布的代码使用的是distinct,这看起来很可能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-14
  • 1970-01-01
相关资源
最近更新 更多