如何在 SQL Server 中进行增量计数

How to count incrementally in SQL Server(如何在 SQL Server 中进行增量计数)
本文介绍了如何在 SQL Server 中进行增量计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被分配了一个问题,我不确定如何在 SQL Server(版本 5/8)中解决.这是简单的查询及其输出:

I am assigned a problem which I am not sure how to solve in SQL Server (version 5/8). Here is the simple query and its output:

Select location, date_time, Item_sold
From Product

Location        Date_time                   Item_sold
VA            12/10/2010 1:30:00 PM           Candy
VA            12/10/2010 3:30:00 PM           Chips
VA            12/13/2010 12:50:00 AM          Wine
DC            12/13/2010 8:00:00 AM           Gum
DC            12/13/2010 12:30:00 PM          Bags
DC            12/13/2010 1:16:00 PM           Cheese
DC            12/13/2010 12:00:00 AM          Hotdog
NJ            12/14/2010 12:00:00 AM          Coffee
NJ            12/14/2010 1:15:00 PM           Beers
NJ            12/14/2010 12:00:00 AM          Coffee
NJ            12/14/2010 1:45:00 PM           Water

这是我想要的输出,我猜一个 while/for 循环或一个 pivot 函数可以完成这项工作,但我的经验还没有.基本上,我需要从 Item_sold 列增量计算已售出的商品数量(基线日期从 12/8 到 12/9、12/8 到 12/10、12/8 到 12/11、12/8 到12 月 12 日...)

Here is my desired output, which I guess a while/for loop or a pivot function could do the job but my experience is not there yet. Basically, I need to count the number of item sold from the Item_sold column incrementally (base line date starts from 12/8 to 12/9, 12/8 to 12/10, 12/8 to 12/11, 12/8 to 12/12...)

Location    12/10 to 12/11  12/10 to 12/12  12/10 to 12/13  12/10 to 12/14
VA               2             2                  3              3
DC               0             0                  3              3 
NJ                 0             0                  0              4

我该如何解决这个问题?

How can I solve this problem?

推荐答案

示例表和数据

create table Product(Location char(2), Date_time datetime, Item_sold varchar(20))
insert Product select 'VA', '20101210 1:30:00 PM' ,'Candy'
insert Product select 'VA', '20101210 3:30:00 PM' ,'Chips'
insert Product select 'VA', '20101213 12:50:00 AM' ,'Wine'
insert Product select 'DC', '20101213 8:00:00 AM' ,'Gum'
insert Product select 'DC', '20101213 12:30:00 PM' ,'Bags'
insert Product select 'DC', '20101213 1:16:00 PM' ,'Cheese'
insert Product select 'DC', '20101213 12:00:00 AM' ,'Hotdog'
insert Product select 'NJ', '20101215 12:00:00 AM' ,'Coffee'
insert Product select 'NJ', '20101215 1:15:00 PM' ,'Beers'
insert Product select 'NJ', '20101215 3:45:00 AM' ,'Cream'

生成所需结果的 T-SQL

The T-SQL to produce the results required

declare @start datetime
declare @end datetime
select @start = '20101208', @end = '20110105'

declare @sql nvarchar(max);
-- generate the column names
select @sql = coalesce(@sql + ',', '') + QuoteName(Convert(char(5),@start,101)+' - '+Convert(char(5),DT,101))
from (
    select @start + number DT
    from master..spt_values
    where type='P' and number between 0 and DATEDIFF(D,@start,@end)) T;

-- replace the column names into the generic PIVOT form
set @sql = REPLACE('
;with COUNTS AS (
    select p.location, Convert(char(5),@start,101)+'' - ''+Convert(char(5),@start + v.number,101) DT, X.C
    from 
    (
        Select distinct location From Product
        where Date_time >= @start and Date_time < @end+1 -- * the date after, to handle the times
    ) p
    inner join master..spt_values v on v.type=''P'' and v.number between 0 and DATEDIFF(D,@start,@end)
    cross apply
    (
        select COUNT(*) C from product p2
        where p2.Location=p.Location
        and p2.date_time >= @start and p2.date_time < @start + v.number +1
    ) X
)
select location, :columns:
from COUNTS p
pivot (max(C) for DT in (:columns:)) pv',
':columns:', @sql)

-- execute for the results
exec sp_executesql @sql, N'@start datetime,@end datetime', @start, @end

这篇关于如何在 SQL Server 中进行增量计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)