I have a table in Clickhouse that stores all the user's transactions, as shown below.
Type is 'debit' or 'credit'
Timestamp is the time when the transaction is recorded.
┌─name────────────┬─type───
│ User │ String │
│ Amount │ String │
│ Type │ String │
│ Category │ String │
│ Timestamp │ Number │
└─────────────────┴────────
I would like to find out the SUM of all the Amount of a specific Category for a user, between a specific Timestamp. If Type = 'debit', then add the amount, if Type = 'credit', subtract the amount.
So if I have the following data, this should be the expected result:
ROW 1
User: 1234
Amount: 10
Type: 'debit'
Category: 'family'
ROW 2
User: 1234
Amount: 3
Type: 'credit'
Category: 'family'
ROW 3
User: 1234
Amount: 3
Type: 'debit'
Category: 'work'
=== RESULT ===
Category: 'family'
Amount: 7
Category: 'work'
Amount: 3
So far I've only gotten through to selecting the transactions between a timestamp.
select User, Amount, Timestamp from transactions t
where t.User = '1234' AND t.Timestamp >= 1663166651 AND p.Timestamp <= 1663266651
I've also tried using the startsWith function to determine credit/debit
select User, sum(if(startsWith(Type, 'debit'), -Amount, Amount)) as Total, Timestamp from transactions t
but I got an error
DB::Exception: Illegal type String of argument of function negate: While processing if(startsWith(Type 'debit')