根据日期计算行与其他行的最大值之间的差值

sqserrrh  于 2021-05-29  发布在  Hadoop
关注(0)|答案(3)|浏览(437)

我有一张table如下:

date          table_name   count_table
2018-07-19    A            50  
2018-07-19    B            40
2018-07-18    A            25
2018-07-18    B            30
2018-07-17    A            10
2018-07-17    B            5

我想计算每个日期的计数差。结果表如下:

date1        date2        table_name    diff
2018-07-17   2018-07-18   A             15
2018-07-18   2018-07-19   A             25
2018-07-17   2018-07-18   B             25
2018-07-18   2018-07-19   B             10 `

谢谢你的帮助

3df52oht

3df52oht1#

SELECT IT1.date1, ITM.date2, IT1.table_name, IT2.count_table - ITM.count_table AS diff
FROM input_table IT1
cross JOIN (
    SELECT *
    FROM input_table IT2
    WHERE IT1.DATE < it2.DATE and IT1.table_name = IT2.table_name)
) ITM
mbskvtky

mbskvtky2#

如果有多个日期和实体,那么您可以使用下面的代码。我刚用mariadb写的。可以通过更改临时表语法在任何数据库中使用。

CREATE TABLE test(dates date, table_name varchar(10), count_table INT);
 INSERT INTO test(dates, table_name, count_table) 
 VALUES('2018-07-19','A', 50),
 ('2018-07-19', 'B', 40),
 ('2018-07-18', 'A', 25),
 ('2018-07-18', 'B', 30),
 ('2018-07-17', 'A', 10),
 ('2018-07-17', 'B', 5);

 CREATE TEMPORARY TABLE test2(dates date, table_name varchar(10), count_table INT, Ranks INT);

INSERT INTO test2
select *, ROW_NUMBER() OVER(partition BY table_name order by dates) as Ranks
from test;

select t1.dates as date1, t2.dates as date2, t1.table_name, t2.count_table - t1.count_table
from test2 t1
INNER JOIN test2 t2 ON t1.table_name = t2.table_name and t1.ranks = t2.ranks - 1
ORDER BY table_name, t1.dates
dldeef67

dldeef673#

在一个查询中使用同一个表两次,并给它一个别名。

SELECT a.date AS date1, b.date AS date2, a.table_name AS table_name, b.count_table - a.count_table AS diff
   FROM yourTable a, yourTable b
   WHERE a.date1 < b.date2
   GROUP BY date1, date2, table_name

相关问题