我在SQL Server中有以下示例数据表
以下是我在消费栏中计算结果的预期结果
答案 0 :(得分:1)
您需要的查询使用具有相同表格的联接:
SELECT KategoriID, ad, odendi, COUNT(odendi)
FROM ogrenci INNER JOIN
taksit ON ogrenci.KategoriID = taksit.KategoriID
WHERE odendi=0
GROUP BY KategoriID
答案 1 :(得分:0)
我在mysql中写了这个并且它有效,如果你需要它用于不同的dbms,请告诉我:fiddle
select t1.item, t1.mydate, t1.reading,
coalesce((t1.reading - t2.reading),0) as consumption
from mytable t1 left join
mytable t2
on t2.item = (select max(item) from
mytable where item < t1.item)
order by t1.item asc
注意:如果您的商品代码每次都不增加1,此代码也会起作用(例如,您有项目1,5,7,8,它将计算5 -1,7 - 5和8-7之间的差异< / p>
编辑:代码也适用于sql-server
答案 2 :(得分:0)
SQL 2012 +:
CREATE TABLE #foobar (item INT, d DATE, reading INT);
INSERT INTO #foobar
( item, d, reading )
VALUES
(1, '2015-06-01', 10),
(2, '2015-06-02', 20),
(3, '2015-06-03', 25);
SELECT *, COALESCE(reading - LAG(reading) OVER (ORDER BY d), 0)
FROM #foobar