在查询中选择导致相反结果的查询

时间:2018-01-17 02:18:44

标签: mysql sql

我在选择查询

中选择显示正确的列时遇到问题
SELECT
      merchant.merchantname  'MerchantName'
    , COALESCE(COUNT(transaction.transactionid),0) 'NoofTransaction'
    , COALESCE(SUM(transaction.transactionamount),0) 'TotalAmount'
    , (         SELECT
                  statement.statementbalance
            FROM statement
            WHERE transaction.transactionid = statement.transactionid
            ORDER BY
                  statementbalance DESC LIMIT 1 
      )                      
      AS 'BalanceRemaining'
FROM merchant
LEFT JOIN transaction ON merchant.merchantid = transaction.merchantid
AND transaction.transactiondate = '2018-01-16'
GROUP BY
      merchant.merchantid
ORDER BY
      merchant.merchantid ASC;

这是从transactionid排序后排队的statementbalance。在我的BalanceRemaining列的日期'2018-01-16'我应该得到7.相反,当sql查询专门按降序排序时,我从所有商家中获得500,并将行限制为1.同样的事情将发生如果我改变它来自transactionid

    statementbalance
    ===
    500
    .
    .
    233
    90
    7

表格的示例数据:http://sqlfiddle.com/#!9/0ec29f

2 个答案:

答案 0 :(得分:1)

您没有按正确的列排序。如果您想要最新日期的值,那么您需要按降序排列DATE和TIME列:

SELECT m.merchantname as MerchantName,
         COALESCE(COUNT(t.transactionid), 0) as NoofTransaction, 
       COALESCE(SUM(t.transactionamount), 0) as TotalAmount,
       (SELECT s.statementbalance
        FROM statement s
        WHERE m.merchantid = s.merchantid
        AND s.statementdate <= '2018-01-16'
        ORDER BY s.statementdate DESC, s.statementtime DESC
        LIMIT 1 
       ) as BalanceRemaining
FROM merchant m 
LEFT JOIN transaction t ON m.merchantid = t.merchantid
                       AND t.transactiondate = '2018-01-16'
GROUP BY m.merchantid
ORDER BY m.merchantid ASC;

要启用此功能,还要更改数据的关联方式,不是通过transactionid,而是通过merchantid。

| MerchantName | NoofTransaction | TotalAmount | BalanceRemaining |
|--------------|-----------------|-------------|------------------|
|         Dog1 |               0 |           0 |           (null) |
|         Cat2 |              13 |         115 |            24.16 |
|      Parrot3 |               1 |          20 |           299.25 |
|      Beaver4 |               0 |           0 |           (null) |

请参阅:http://sqlfiddle.com/#!9/cc2440/3

答案 1 :(得分:0)

如果你想要&#34; 7&#34;,或许你想要ASC排序而不是DESC排序。

我还建议使用表别名:

SELECT m.merchantname as MerchantName,
       COUNT(t.transactionid), 0) as NoofTransaction, 
       COALESCE(SUM(t.transactionamount), 0) as TotalAmount,
       (SELECT s.statementbalance
        FROM statement s
        WHERE t.transactionid = s.transactionid
        ORDER BY statementbalance ASC
        LIMIT 1 
       ) as BalanceRemaining
FROM merchant m LEFT JOIN
     transaction t
     ON m.merchantid = t.merchantid AND t.transactiondate = '2018-01-16'
GROUP BY m.merchantid
ORDER BY m.merchantid ASC;

注意:

  • 表别名使查询更易于编写和阅读。
  • 仅对字符串和日期常量使用单引号。不要将它们用于列别名。
  • 我建议使用as列别名。
  • COUNT()永远不会返回NULL,因此COALESCE()是不必要的。