我同意@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]
下面是從外部的結果選擇:
這裏的(自身數據表Y)從內部選擇的結果:
很不清楚的問題,說實話與你...嘗試完全重寫它。你有什麼輸入? 2.你想作爲輸出?你如何試圖達到你的目標? – Smarty 2012-02-25 12:13:42
我想總結上表的數據月明智..對於前。用戶名xyz從他的軟件包開始時開始搜索34名員工(猜測每年的軟件包) - 上面的例子數據有50個搜索可用於他的軟件包..所以每個月他可以搜索50,如果超過50,那麼我希望單獨計數。 – 2012-02-25 16:18:50