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

2023-12-02

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

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 循环或枢纽函数可以完成这项工作,但我的经验还没有。基本上,我需要递增地计算 Item_sold 列中售出的商品数量(基线日期从 12/8 到 12/9、12/8 到 12/10、12/8 到 12/11、12/8 到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

我怎么解决这个问题?


示例表和数据

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 产生所需的结果

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在SQL Server中进行增量计数 的相关文章

随机推荐

  • 更改枚举 Swift 的关联值

    如何更改枚举的特定关联值 enum Origin case search searchTerm String filtered Bool case category categoryName String subcategoryName S
  • 异步函数中的变量范围

    我已经构建了返回一些变量的函数 但我的函数异步使用另一个函数 function getVariable var myVariable asyncronousFunction function myVariable return myVari
  • 比较同一文档的两个字段[重复]

    这个问题在这里已经有答案了 我正在尝试查询一个巨大的 mongo 集合 其中包含大约 50 百万条记录 在 mongo 查询中 我只需要几个字段 文档中存在的对象 ID 和 MD5 为此 我做了 Query db getCollection
  • Android动画不重复

    我正在尝试制作会重复多次 或无限 的简单动画 看起来android repeatCount不起作用 这是我的动画资源 res anim first animation xml
  • 将字符串传递给python中的文件打开函数

    我有一个用户输入 我想将其作为打开函数的文件名参数传递 这是我尝试过的 filename input Enter the name of the file of grades file open filename r 当用户输入的是open
  • PHP 字符串替换

    我有字符串 var 我需要在其中替换一些文本 第一个 X 需要替换为 A 第二个 X 需要替换为B等等 下面是一个例子 我尝试过str replace但这行不通 Thanks 你可以使用preg replace s limit只替换一次的说
  • 如何在AWS S3中添加缓存控制?

    我已通过 s3cmd 命令将 20000 个文件移动到 AWS S3 现在我想为所有图像添加缓存控制 jpg 这些文件位于 s3 bucket name images 如何通过 s3cmd 为所有图像添加缓存控制或者是否有其他方法来添加标头
  • Facebook Like Box 无法在 Ember 应用程序上加载

    我试图让类似的框在我们的 ember 应用程序中工作 在一个名为的模板中about 问题是 如果我从另一条路线进入 ember 应用程序 而不是about路线 然后导航至about路线与link to助手 则不会呈现类似框 相反 如果我输入
  • Dagger 2.0 - AppEngine - gradle 配置

    我正在尝试在 AppEngine 项目中从 Dagger 1 2 2 迁移到 Dagger 2 0 1 NOT安卓一 使用 Dagger 1 2 2 很简单 compile com squareup dagger dagger compil
  • 在 iOS 中,如何使用 Xcode 从 Localized.strings 中删除语言

    这就是我的 xcode 项目的样子 我想删除英国和美国的 Localized strings 只保留英语的 Localized strings 我怎样才能做到这一点 按照下图中的说明进行操作
  • 道场声明正确的方式

    file dojo dir1 utils XmlJsonUtils js Author Rajat Khandelwal define dojo base declare declare function declare return de
  • OpenCart 管理菜单链接 url

    我对 OpenCart 很陌生 我正在尝试为其制作一个模块 我想要在管理菜单中链接到我正在创建的模块 因此我编辑了此文件 admin view template common header tpl 我添加的代码 li a class top
  • 时间:2019-03-17 标签:c#Array.FindAllIndexOfwhichFindAllIndexOf

    我知道c 有Array FindAll and Array IndexOf 有没有Array FindAllIndexOf返回int string myarr new string s f s int v myarr Select b i
  • 在 for 循环中处理“借用的值没有足够长的寿命”[重复]

    这个问题在这里已经有答案了 我正在抓取的网站要求我查询 HTML 页面的标题标签以及一些其他元素 看看我是否可以辨别文章的标题 我创建一个HashMap lt str u8 gt 并立即 insert title tag text 1 查询
  • 后台线程上的 NSTimer 回调

    我有一个NSTimer定义如下 timer NSTimer scheduledTimerWithTimeInterval 30 target self selector selector fooBar userInfo nil repeat
  • 选择以“abc”开头并以“xyz”结尾的元素

    我的页面中有一些 id 类似于 abc 1 2 3 xyz 的元素 如何在 Jquery 中选择以 abc 开头并以 xyz 结尾的元素 div id abc div id xyz 您可以使用 2 个属性选择器 div id abc id
  • 函数式接口的行为和方法参考

    当属于变量的方法的引用被销毁时会发生什么 public class Hey public double bar public Hey bar 2 0d public double square double num return Math
  • 基于定义C#更改exe图标

    我正在为两个不同的人创建一个项目 我想通过定义更改图标 例如 if customer1 add code to select c path to resources myimage1 ico for exe icon else add co
  • 如何计算列表中唯一列表的数量?

    我尝试过使用 Counter 和 itertools 但由于列表不可获取 因此它们不起作用 我的数据如下所示 1 2 3 2 3 4 1 2 3 我想知道列表 1 2 3 出现两次 但我不知道如何做到这一点 我正在考虑将每个列表转换为一个元
  • 如何在SQL Server中进行增量计数

    我被分配了一个问题 我不确定如何在 SQL Server 版本 5 8 中解决 这是简单的查询及其输出 Select location date time Item sold From Product Location Date time