【问题标题】:postgresql query to get sum and columns from two tables using joinspostgresql 查询使用连接从两个表中获取总和和列
【发布时间】:2022-01-24 06:28:21
【问题描述】:

这些是我创建的表:Tables

  1. 我想从 '10-11-2021' 和 '31-12- 之间的两个表中获取 accounts.account,accounts.type,DATE(transactions.date),transactions.transactionid,transactions.amount,transactions.note- 2021'.(无论是什么类型)

  2. 我想从 type="income" 和 '10-11-2021' 和 '31-12-2021' 之间的交易表中获取 Sum(account)。

  3. 我想从 type="expense" 且介于 '10-11-2021' 和 '31-12-2021' 之间的交易表中获取 Sum(account)。

但是我需要在一个语句中所有三个查询(这就是我正在努力的)

我的查询:

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'

我还需要添加其他两个查询以适应上述情况

谁能帮帮我?

【问题讨论】:

    标签: c# sql postgresql asp.net-core-mvc query-string


    【解决方案1】:

    鉴于有关源表的信息很差,我能做到的最好的方法如下:

    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)
    

    提示:您不应该用单行代码编写 sql 脚本,几乎从不。

    如果有表格内容,或者至少是屏幕截图,也可以提供更多信息。

    【讨论】:

    • 可能无法“按原样”工作可能是您必须以某种方式调整代码以匹配您想要的输出,但希望您能理解
    • 感谢您回答问题,但 transactions 表中没有名为“type”的列,它在 accounts 表中。在写这个“sum(case when t.type = 'income' then t.amount else 0 end) sum_of_income”时,你已经放了transactions.type所以有一个错误
    • 您能提供有关表格数据的任何信息吗?
    猜你喜欢
    • 1970-01-01
    • 2021-01-26
    • 2015-11-02
    • 2015-07-05
    • 2020-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    相关资源
    最近更新 更多