在select查询中选择查询

时间:2018-01-16 02:17:27

标签: mysql

    SELECT
  merchant.merchantname 'MerchantName',
  COUNT(transaction.transactionid) 'NoofTransaction',
  SUM(transactionamount) 'TotalAmount'
    (SELECT statement.statementbalance from statement where transactionid = statement.transactionid ORDER BY merchantid LIMIT 1) AS 'BalanceRemaining'
  FROM transaction
  RIGHT JOIN merchant ON transaction.merchantid = merchant.merchantid
    RIGHT JOIN statement ON transaction.transactionid = statement.transactionid
  WHERE transaction.transactiondate = '2018-01-15'
  GROUP BY merchant.merchantid;
    ORDER BY merchant.merchantid ASC;

我试图在选择查询中选择一个查询,允许我选择余下余额的最后插入结果。

1 个答案:

答案 0 :(得分:1)

我想以下针对您的需求的修订查询没有连接到语句表,因为这样的连接可能会增加行数,从而在结果中产生错误。

SELECT
      merchant.merchantname  'MerchantName'
    , COUNT(t.transactionid) 'NoofTransaction'
    , SUM(t.transactionamount) 'TotalAmount'
    , (
            SELECT
                  statement.statementbalance
            FROM statement
            WHERE t.transactionid = statement.transactionid
            ORDER BY
                  some_date_column DESC LIMIT 1 
      )                      
      AS 'BalanceRemaining'
FROM merchant
INNER JOIN `transaction` t ON merchant.merchantid = t.merchantid
WHERE t.transactiondate = '2018-01-15'
GROUP BY
      merchant.merchantid
ORDER BY
      merchant.merchantid ASC
;

注意,问题中没有给出用于订购的日期栏(“最后插入”)。

我也改变了表关系。在我的视图中使用右连接没有多大意义,因为构造查询以使用“from table”几乎总是更容易,因此后续连接永远不需要正确的连接。在这种特殊情况下,由于where子句,似乎不需要任何形式的外连接,因此使用内连接。

已添加:列出所有商家:

SELECT
      merchant.merchantname  'MerchantName'
    , COUNT(t.transactionid) 'NoofTransaction'
    , SUM(t.transactionamount) 'TotalAmount'
    , (
            SELECT
                  statement.statementbalance
            FROM statement
            WHERE t.transactionid = statement.transactionid
            ORDER BY
                  some_date_column DESC LIMIT 1 
      )                      
      AS 'BalanceRemaining'
FROM merchant
LEFT JOIN `transaction` t ON merchant.merchantid = t.merchantid
                         AND t.transactiondate = '2018-01-15'
GROUP BY
      merchant.merchantid
ORDER BY
      merchant.merchantid ASC
;