在一个查询中计算三个表?

时间:2013-11-28 21:17:11

标签: mysql sql

我有三张桌子:发票,付款和退款。我希望按类型获得txn计数,按月/年分组。

我正在寻找类似的结果:

Month-Year    Invoices    Payments    Refunds
01-2013        32432        534        32
02-2013        4323        789         53

我可以通过以下方式获得单个表计数(减去一些转换):

SELECT
    YEAR(txndate)
    , MONTH(txndate)
    , COUNT(*)
    , "Invoice" AS type
FROM invoices
GROUP BY
    YEAR(txndate)
   , MONTH(txndate)

如果归结为它,我可以做三个查询(每个表一个)然后合并我的结果,但我认为必须有一个更聪明的方法。

每个表都有一个TxnDate列。

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

不确定这是否真的更容易,但你可以用一堆UNION来构建类似的东西:

SELECT year, month, SUM(invoice) AS invoices, SUM(payment) AS payments, SUM(refund) AS refunds
FROM (SELECT YEAR(txndate) AS year, MONTH(txndate) AS month, 
             1 AS invoice, 0 AS payment, 0 AS refund
      FROM   invoices 
      UNION ALL
      SELECT YEAR(txndate) AS year, MONTH(txndate) AS month, 
             0 AS invoice, 1 AS payment, 0 AS refund
      FROM   payments
      UNION ALL
      SELECT YEAR(txndate) AS year, MONTH(txndate) AS month, 
             0 AS invoice, 0 AS payment, 1 AS refund
      FROM   refunds) t
GROUP BY year, month

答案 1 :(得分:0)

您可以尝试这样的事情,在

之前添加选择
SELECT

(SELECT COUNT(*)
FROM invoices
WHERE YEAR(txndate) = YEAR(main.txndate) AND MONTH(txndate) = MONTH(main.txndate))
as invoices,

(SELECT COUNT(*)
FROM payments
WHERE YEAR(txndate) = YEAR(main.txndate) AND MONTH(txndate) = MONTH(main.txndate))
as payments,

(SELECT COUNT(*)
FROM refunds
WHERE YEAR(txndate) = YEAR(main.txndate) AND MONTH(txndate) = MONTH(main.txndate))
as refunds

FROM invoices as main
GROUP BY YEAR(txndate), MONTH(txndate)