用于月份计数的SQL查询

时间:2012-02-25 12:01:38

标签: sql-server sql-server-2008 tsql

我有以下表格用于包裹及其每月计数,例如..

Package1 - 每次搜索1美元 - 包含50个搜索(每月),额外搜索FOR MONTH将另行计算。

我在表格中传递数据,如..

用户包表包含用户的包信息及其详细信息。

UserpackageId  Userid  PackageId  SearchPerMonth    StartDatePackage    EndDatePackage
1                1         1             50         25/02/2012         25/02/2013  (1 YEAR)

明细表

Userpackageid      SearchDate      SearchCost      
1                  26/02/2012       1 Dollor

现在我想总结一下像

这样的数据

每月包裹搜索次数 - 因为我每个月都会搜索50个包裹...如果额外的数量超过50,那么它将显示其他数量的额外数量。每月智能...

1 个答案:

答案 0 :(得分:0)

我同意@Smarty你的问题很难阅读,所以我必须对你的要求作出一些假设。

看看这对你有帮助。

create table UserPackage(ID int identity(1,1), UserID int, PackageID int,
    SearchPerMonth int, StartDate datetime, EndDate datetime)
create table Detail(ID int identity(1,1), UserPackageID int, SearchDate datetime,Cost money)

insert into UserPackage(UserID, PackageID, SearchPerMonth, StartDate, EndDate) 
    values(1,1,3,'2/15/12','2/15/13')

insert into Detail(UserPackageID,SearchDate,Cost) values(1,'2/16/12',1)
insert into Detail(UserPackageID,SearchDate,Cost) values(1,'2/17/12',2)
insert into Detail(UserPackageID,SearchDate,Cost) values(1,'2/18/12',3)
insert into Detail(UserPackageID,SearchDate,Cost) values(1,'2/19/12',4)
insert into Detail(UserPackageID,SearchDate,Cost) values(1,'2/20/12',5)

select 
    UserPackageID,
    CostInLimit=sum(CostInLimit),
    CostAboveLimit=sum(CostAboveLimit)
from
    (
    select
        z.UserPackageID,
        z.DetailID,
        IsInLimit=case when z.RankInMonth > up.SearchPerMonth then 1 else 0 end,
        CostInLimit=case when z.RankInMonth > up.SearchPerMonth then Cost else 0 end,
        CostAboveLimit=case when z.RankInMonth > up.SearchPerMonth then 0 else Cost end,
        z.Cost,
        z.RankInMonth,
        z.SearchDate
    from
        UserPackage up
        inner join
        (
            select
                DetailID=ID,
                UserPackageID,
                Cost,
                RankInMonth=RANK() OVER (PARTITION BY UserPackageID ORDER BY SearchDate),
                SearchDate
            from 
                Detail 
        ) z on z.UserPackageID = up.ID
    ) y 
where
    y.SearchDate between '2/15/12' and '3/15/12'
group by
    UserPackageID][1]

以下是外部选择的结果:

enter image description here

这是内部选择的结果(表y本身): enter image description here