我有这样的数据库:
weekid overage type type2
504 400 x y
504 400 z y
503 200 x z
502 100 x x
502 100 x y
我想要的是将400从weekid 504获得与200的weekid 503和100来自weekid 502,我不希望它将其他400与payid 504或502相加
因此输出应为sum(overage)= 700
基本上我想要的是像这样执行vbscript循环的东西
do until rs9.eof
if weekid<>rs.fields("weekid") then
weekid=rs.fields("weekid")
overage=overage+rs.fields("overage")
end if
rs.movenext
loop
但它需要在查询中执行此操作,执行此操作的最简单的SQL查询是什么?
我的sql server版本似乎也不支持row_number
答案 0 :(得分:2)
试试这个;
如果相同的星期几的值总是相同,则使用a) 对于相同的星期几具有不同的超额值的情况:
a)如果您需要将相同值的不同值包含在总和中:
SELECT SUM([Overage])
FROM ( SELECT DISTINCT
[WeekId] ,
[Overage]
FROM [dbo].[OverageTable]
) tmp
a)如果您只需要将相同值的不同值的最大值包含在总和中:
SELECT SUM([Overage])
FROM ( SELECT [WeekId] ,
MAX([Overage]) AS [Overage]
FROM [dbo].[OverageTable]
GROUP BY [WeekId]
) tmp
答案 1 :(得分:0)
这取决于第一行的含义 - 数据没有固有的顺序。
当您决定如何订购时,可以调整下面的order by
条款。
select sum(overage)
from
(Select overage, row_number() over (partition by weekid order by type, type2) rn
from yourtable
) v
where rn=1
答案 2 :(得分:0)
您可以随机选择一个值:
select sum(overage)
from (select t.*,
row_number() over (partition by weekid order by newwid()) as seqnum
from t
) t
where seqnum = 1
如果您知道所有值都相同,则可能更喜欢聚合:
select sum(overage)
from (select weekid, max(overage) as overage
from t
group by weekid
) t
不要做以下事项:
select sum(distinct overage)
虽然这是有效的SQL,但您将失去具有相同值的周数。