简体   繁体   中英

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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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