简体   繁体   English

postgresql 查询使用连接从两个表中获取总和和列

[英]postgresql query to get sum and columns from two tables using joins

These are the tables that I have created: Tables这些是我创建的表:

  1. I want to get accounts.account,accounts.type,DATE(transactions.date),transactions.transactionid,transactions.amount,transactions.note from two tables between '10-11-2021' and '31-12-2021'.(whatever type may be)我想从'10-11-2021'和'31-12-2021'之间的两个表中获取accounts.account,accounts.type,DATE(transactions.date),transactions.transactionid,transactions.amount,transactions.note。 (无论是什么类型)

  2. I want to get Sum(account) from transactions table where type="income" and between '10-11-2021' and '31-12-2021'.我想从类型=“收入”以及“10-11-2021”和“31-12-2021”之间的交易表中获取 Sum(account)。

  3. I want to get Sum(account) from transactions table where type="expense" and between '10-11-2021' and '31-12-2021'.我想从 type="expense" 和 '10-11-2021' 和 '31-12-2021' 之间的交易表中获取 Sum(account)。

But I need all three queries in a single statement(that's what I am struggling)但我需要在一个语句中的所有三个查询(这就是我正在努力的)

My query:我的查询:

SELECT  accounts.account,accounts.type,DATE(transactions.date),transactions.transactionid,transactions.amount,transactions.note
FROM transactions
FULL JOIN accounts ON transactions.accountid=accounts.accountid
WHERE transactions.date BETWEEN '{0}' AND '{1}' ORDER BY transactions.date
UNION
  select sum(amount)
  FROM transactions
  FULL JOIN accounts ON transactions.accountid=accounts.accountid 
  WHERE accounts.type='income'

I need to add other two queries also to fit above我需要添加其他两个查询也适合上面

can anyone help me?谁能帮我?

Given the poor information about the source tables, the best I could is the following:鉴于有关源表的信息很差,我能做到的最好的方法如下:

SELECT  
        a.account,
        a.type,
        DATE(t.date),
        sum(case when t.type = 'income' then t.amount else 0 end) sum_of_income,
        sum(case when t.type = 'expense' then t.amount else 0 end) sum_of_expense

FROM transactions t 
left JOIN accounts a
    ON t.accountid = a.accountid 
group by
    a.account,
    a.type,
    DATE(t.date)

tip: you shouldn't write your sql script in single-line code, almost never.提示:你不应该用单行代码编写 sql 脚本,几乎从不。

Also could be more informative to have table contents, or at least screenshots.拥有表格内容或至少是屏幕截图也可能会提供更多信息。

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

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