选择使用具有多个条件的子查询的带计算字段的查询

q3aa0525  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(361)

三张table:
成本节约:成本节约id、一次性信贷、创建日期、发票id(fk到发票表)
发票:发票\标识,发票\货币\代码
汇率:货币汇率,货币日期
我在报告成本节约(第一个表)。挑战在于,每个成本节约金额可以使用不同的货币,因此我需要一个字段,该字段显示基于发票表中的货币以及exchange.ex\u日期和cost\u savings.create\u日期之间匹配的月/年的换算金额。
我得到一个错误,说明:
单行子查询返回多行
到目前为止,我的情况是:

SELECT 
COST_SAVINGS.COST_SAVINGS_ID, 
COST_SAVINGS.CLAIM_TYPE, 
COST_SAVINGS.COMMENTS, 
COST_SAVINGS.COST_SAVINGS_STATUS, 
COST_SAVINGS.CREATION_DATE, 
COST_SAVINGS.DESCRIPTION,
COST_SAVINGS.ONE_TIME_CREDIT AS CREDIT_IN_NATIVE_CURRENCY,
FINANCE_INVOICE.CURRENCY_CODE,
COST_SAVINGS.ONE_TIME_CREDIT * 
    (SELECT EXCHANGE_RATE.CURRENCY_RATE 
     FROM EXCHANGE_RATE 
     WHERE EXTRACT (MONTH FROM COST_SAVINGS.CREATION_DATE) = EXTRACT (MONTH FROM EXCHANGE_RATE.CURRENCY_DATE)
     AND EXTRACT (YEAR FROM COST_SAVINGS.CREATION_DATE) = EXTRACT (YEAR FROM EXCHANGE_RATE.CURRENCY_DATE)
     AND FINANCE_INVOICE.CURRENCY_CODE = EXCHANGE_RATE.CURRENCY_CODE) AS CREDIT_IN_USD

FROM COST_SAVINGS

LEFT JOIN FINANCE_INVOICE ON COST_SAVINGS.INVOICE_ID = FINANCE_INVOICE.INVOICE_ID

我觉得问题可能出在我的子查询中的第三个where子句(试图匹配货币代码)。我不知道该怎么解决。有什么想法吗?

fcwjkofz

fcwjkofz1#

试着把 LIMIT 1 在子查询中:

...RENCY_CODE = EXCHANGE_RATE.CURRENCY_CODE LIMIT 1) AS CREDIT_IN_USD

我相信您的子查询返回了多行。如果在查询中使用子查询代替列名,则这不起作用 SELECT 条款。
如果您不想用子查询来代替列名,可以这样做。您将连接到子查询生成的虚拟表。
这是虚拟的汇率表。它使用 GROUP BY 每个月/年/货币代码生成一行(或不生成行)。如果任何月/年/代码的原始表中有多行,则它们将使用 AVG() . 你也可以用 MAX() 或者 MIN() .

SELECT AVG(CURRENCY_RATE) CURRENCY_RATE,
                 CURRENCY_CODE,
                 EXTRACT(MONTH FROM CURRENCY_DATE) MONTH,
                 EXTRACT(YEAR FROM CURRENCY_DATE) YEAR
            FROM EXCHANGE_RATE 
           GROUP BY CURRENCY_CODE, 
                 EXTRACT(MONTH FROM CURRENCY_DATE),
                 EXTRACT(YEAR FROM CURRENCY_DATE)

试试这个,让自己相信它是有效的。
然后将其构建到整个查询中。

SELECT 
      COST_SAVINGS.COST_SAVINGS_ID, 
      COST_SAVINGS.whatever,   ...   
      FINANCE_INVOICE.CURRENCY_CODE,
      (COST_SAVINGS.ONE_TIME_CREDIT * RATE.CURRENCY_RATE) AS CREDIT_IN_USD
FROM COST_SAVINGS
LEFT JOIN FINANCE_INVOICE ON COST_SAVINGS.INVOICE_ID = FINANCE_INVOICE.INVOICE_ID
LEFT JOIN (SELECT AVG(CURRENCY_RATE) CURRENCY_RATE,
                 CURRENCY_CODE,
                 EXTRACT(MONTH FROM CURRENCY_DATE) MONTH,
                 EXTRACT(YEAR FROM CURRENCY_DATE) YEAR
            FROM EXCHANGE_RATE 
           GROUP BY CURRENCY_CODE, 
                 EXTRACT(MONTH FROM CURRENCY_DATE),
                 EXTRACT(YEAR FROM CURRENCY_DATE)
    ) RATE ON RATE.CURRENCY_CODE = FINANCE_INVOICE.CURRENCY_CODE
          AND RATE.YEAR  = EXTRACT(YEAR  FROM COST_SAVINGS.CREATION_DATE)
          AND RATE.MONTH = EXTRACT(MONTH FROM COST_SAVINGS.CREATION_DATE)

相关问题