当您说分区时,我很好奇您是指在窗口函数中还是在一般情况下对数据进行分组。让我在一个自我演示的示例中向您展示两种聚合数据并对其进行分区的方法:
declare @Orders table( id int identity, dt date, counts int)
insert into @Orders values ('1-1-12', 2),('1-1-12', 3),('1-18-12', 1),('2-11-12', 5),('3-1-12', 2),('6-1-12', 8),('10-1-12', 2),('1-13-13', 8)
-- To do days I need to do a group by
select
dt as DayDate
, SUM(counts) as sums
from @Orders
group by dt
-- To do months I need to group differently
select
DATEADD(month, datediff(month, 0, dt), 0) as MonthDate
-- above is a grouping trick basically stating count from 1/1/1900 the number of months of difference from my date field.
--This will always yield the current first day of the month of a date field
, SUM(counts) as sums
from @Orders
group by DATEADD(month, datediff(month, 0, dt), 0)
-- well that is great but what if I want to group different ways all at once?
-- why windowed functions rock:
select
dt
, counts
, SUM(counts) over(partition by DATEADD(year, datediff(year, 0, dt), 0)) as YearPartitioning
, SUM(counts) over(partition by DATEADD(month, datediff(month, 0, dt), 0)) as MonthPartitioning
-- expression above will work for year, month, day, minute, etc. You just need to add it to both the dateadd and datediff functions
, SUM(counts) over(partition by dt) as DayPartitioning
from @Orders
关于分组的重要概念是传统的 group by 子句,您必须将不执行数学运算的子句列为要处理的枢轴。所以在我的第一个选择中,我只选择了日期,然后说 sum(counts)。然后它在 1-1-12 上看到它有两个值,因此它添加了它们,并在其他所有东西上单独添加了它们。在第二种选择方法中,我对日期字段执行了一个技巧,以使其转换为该月的第一天。现在这很棒,但我可能想要一次所有这些。
窗口函数内联进行分组,这意味着它们不需要分组子句,因为这就是 over() 部分所做的。但是,它可能会重复这些值,因为您没有限制数据集。这意味着如果您查看第三个选择“YearPartitioning”的第三列,它会重复数字 23 七次。为什么?好吧,因为您从未告诉该语句在函数之外进行任何分组,因此它显示了每一行。只要所有值的年份都相同的表达式为真,数字 23 就会出现。从窗口表达式中选择时请记住这一点。