简体   繁体   English

分组和连接同一个表中的行 - SQLite

[英]Grouping and joining rows in same table - SQLite

I have a table that stores double value, int type (either 0 or 1) and another integer column for store timestamp in unixepoch.我有一个表,用于存储 double 值、int 类型(0 或 1)和另一个整数列,用于在 unixepoch 中存储时间戳。

I want to get the difference of sums of types for each month.我想获得每个月类型总和的差异。 But I couldn't figure out a way to join rows since the join condition is based on group by value.但是我想不出连接行的方法,因为连接条件基于按值分组。

I can get the sum for each type in each month by running the below query.我可以通过运行以下查询获得每个月每种类型的总和。

SELECT strftime('%Y-%m', date(dt/1000, 'unixepoch')) AS groupDate, ty, SUM(am) AS total 
FROM tr
WHERE (dt BETWEEN 1621185800000 AND 1625077799000) AND ty IN (1, 0)
GROUP BY strftime('%Y-%m', date(dt/1000, 'unixepoch')), ty
2021-05 0   1200.0 <- Difference of this
2021-05 1   500.0  <- and this in a single row like 2021-05 700.0
2021-06 0   2500.0
2021-06 1   150.0

But I want to get an output like this.但我想得到这样的输出。 I can process the above in the application layer and get the desired output.我可以在应用程序层处理上述内容并获得所需的输出。 But I'm wondering is there any way to get from the database itself since it will be more efficient and robust.但我想知道有什么方法可以从数据库本身获取,因为它会更高效和健壮。

2021-05 700.0
2021-06 2350.0

Thanks.谢谢。

You can use conditional aggregation like this:您可以像这样使用条件聚合:

SELECT strftime('%Y-%m', date(dt/1000, 'unixepoch')) AS groupDate, 
       SUM(CASE WHEN ty = 0 THEN am ELSE - am END) AS total 
FROM tr
WHERE dt BETWEEN 1621185800000 AND 1625077799000 AND
      ty IN (1, 0)
GROUP BY strftime('%Y-%m', date(dt/1000, 'unixepoch'));

Or, if you don't like CASE expressions:或者,如果您不喜欢CASE表达式:

       SUM( (1 - ty) * am ) AS total 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM