简体   繁体   English

SQL Over分区依据

[英]SQL Over partition by

I basically have a case statement that displays the sum of profit and a month to date total for each person. 我基本上有一个案例声明,显示每个人的利润之和和一个月至今的总额。 My idea is i want to display a daily figure of that person as well as their whole month total altogether. 我的想法是我要显示该人的每日数字以及他们整个月的全部时间。

My issue is when i limit results to just yesterday (supposed to be a daily figure) this then effects the calculation of the month value (just calculates the sum for that day rather than the whole month). 我的问题是,当我将结果限制为昨天(应该是每日数字)时,这会影响月份值的计算(只是计算当天的总和,而不是整个月)。

This is because the total month values are all out of the scope of the query. 这是因为月份总数值都超出了查询范围。 Is there anyway to calculate the whole month value for each person correctly without having the limits of where effecting the result. 无论如何,是否可以正确计算每个人的整个月值,而没有影响结果的限制。

eg The result: 例如结果:

08/09/17:    25    
09/09/17:    25   
10/09/17:    25    
11/09/17:    25  <<<< but only display one day and month total
Overall Month total: 100 

Can this also includes nulls too? 这也可以包括空值吗? I think im almost looking at a dynamically stored month to date value that isn't effected by where clauses. 我认为即时通讯几乎要查看不受where子句影响的动态存储的月初至今值。

SELECT SUM(Figure) AS 'Daily Figure',

CASE WHEN 
    MONTH([DATE]) = MONTH(getdate()) AND
        YEAR([DATE]) = YEAR(getdate())
THEN  
SUM(Figure)
OVER (PARTITION BY [Name], 
MONTH([DATE])) 
ELSE 0 END 
as [Month To Date Total]

WHERE 
    dateadd(day,datediff(day,1,GETDATE()),0)

If you want month-to-date and the current amount, then use conditional aggregation: 如果您希望获得当月和当前的金额,请使用条件聚合:

SELECT NAME,
       SUM(CASE WHEN DAY(DATE) = DAY(GETDATE()) - 1 THEN Figure ELSE 0 END) AS DailyFigure,  
       SUM(Figure) as MonthToDate      
WHERE MONTH([DATE]) = MONTH(getdate()) AND
      YEAR([DATE]) = YEAR(getdate())
GROUP BY NAME;

This works on all but the first day of the month. 除每月的第一天外,此功能均适用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM