友 我有一个数据库,我保持所有用户的流量。它每天都会更新。 我想计算每天的流量。这意味着:今天的流量 - 昨天的流量?
有三个表(向下,向上,远程)。有结果:
select rem.remoteid, down.mazgas, down.portas, down.down, up.up, down.date
from dbo.remoteid as rem
inner join dbo.down as down on down.mazgas=rem.mazgas and down.portas = rem.portas
inner join dbo.up as up on up.mazgas=down.mazgas and up.portas = down.portas
where down.mazgas=up.mazgas and down.portas=up.portas and down.date= up.date
result
remoteid mazgas portas down up date
10156529 10.199.100.27 gpon-onu_1/12/5:1 2678.0 69963.9 2014-06-01
10156529 10.199.100.27 gpon-onu_1/12/5:1 2643.8 68912.3 2014-05-31
29546232 10.203.100.1 gpon-onu_1/16/1:4 927.8 39273.6 2014-06-01
29546232 10.203.100.1 gpon-onu_1/16/1:4 923.1 39126.7 2014-05-31
我想得到一个答案:
remoteid, mazgas, portas, down, up where down = (down(today) - down(yesterday)) and up= (up(today) - up(yesterday))
非常感谢你。
答案 0 :(得分:0)
由于您没有指定您正在使用的RDBMS,我将尝试使用基本SQL。这样的东西会给你想要的结果:
SELECT
r.remoteid,
r.mazgas,
r.portas,
COALESCE(d2.down,0)-COALESCE(d1.down,0) AS down,
COALESCE(u2.up ,0)-COALESCE(u1.up ,0) AS up,
d2.date
FROM dbo.remoteid AS r
JOIN dbo.down AS d2 ON d2.mazgas=r.mazgas AND d2.portas=r.portas
LEFT JOIN dbo.up AS u2 ON u2.mazgas=r.mazgas AND u2.portas=r.portas AND u2.date=d2.date
LEFT JOIN dbo.down AS d1 ON d1.mazgas=r.mazgas AND d1.portas=r.portas AND d1.date=(
SELECT MAX(date)
FROM dbo.down
WHERE mazgas=r.mazgas AND portas=r.portas AND date<d2.date)
LEFT JOIN dbo.up AS u1 ON u1.mazgas=r.mazgas AND u1.portas=r.portas AND u1.date=(
SELECT MAX(date)
FROM dbo.up
WHERE mazgas=r.mazgas AND portas=r.portas AND date<u2.date)
需要考虑的事项:
这不会给你与昨天的价值有所区别,但与最后一个有价值的日期的差异(相同的马兹加和波塔斯)。如果所有日期都有值,那么结果是相同的。
你想要的是一些日期代数,比如这个简单的-1语法:
SELECT
r.remoteid,
r.mazgas,
r.portas,
COALESCE(d2.down,0)-COALESCE(d1.down,0) AS down,
COALESCE(u2.up ,0)-COALESCE(u1.up ,0) AS up,
d2.date
FROM dbo.remoteid AS r
JOIN dbo.down AS d2 ON d2.mazgas=r.mazgas AND d2.portas=r.portas
LEFT JOIN dbo.up AS u2 ON u2.mazgas=r.mazgas AND u2.portas=r.portas AND u2.date=d2.date
LEFT JOIN dbo.down AS d1 ON d1.mazgas=r.mazgas AND d1.portas=r.portas AND d1.date=d2.date-1
LEFT JOIN dbo.up AS u1 ON u1.mazgas=r.mazgas AND u1.portas=r.portas AND u1.date=u2.date-1
...但是不同的RDBMS可能会以其他方式处理日期代数(它们都有一些要添加的功能,但是减去天数)。
就效率而言...... 你最好在mazgas,portas,down table和up table上的日期上有索引;)