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

xzlaal3s  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(315)

在select查询中显示select中的正确列时遇到问题

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队列。在我的平衡器主列上的日期 '2018-01-16' 我应该7岁了。相反,当sql查询明确地按降序排序并将行限制为1时,我一直从列出的所有商户中获取500。如果我将其更改为从transactionid获取,也会发生同样的事情

statementbalance
    ===
    500
    .
    .
    233
    90
    7

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

lskq00tm

lskq00tm1#

您没有按正确的列排序。如果需要最新日期的值,则需要按日期和时间列降序排列:

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号

w6mmgewl

w6mmgewl2#

如果你想要“7”,也许你想要一个 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() 是不必要的。

相关问题