mysql - 如何在sql中对2个不同的列进行排序

标签 mysql sql

你们能告诉我如何在 sql 中对用户定义列和固定列名进行排序吗?我需要显示最高交易和outletid,而我只得到最高交易但outlet id不在分组中。

对不起,我的英语很差

问题来了

outlet id | revenue code | total transaction | total amount

6837      |     014  |        326        |   39158.94
6821      |     408  |        291        |   48786.50
6814      |     014  |        285        |   74159.76
6837      |     452  |        282        |   8846.80

这是我的sql

SELECT 
                outletid, 
                revcode,
                count(receiptnumbe) as Transactions,
                sum(amount) as total
            FROM 
                user_payment
            WHERE
                date = (SELECT MAX(date) FROM user_payment GROUP BY date desc LIMIT 0, 1)
            GROUP BY 
                outletid, revcode
            ORDER BY Transactions desc

我需要它是这样的。按网点 ID 和最高交易排序。

outlet id | revenue code | total transaction | total amount

    6837      |     014  |        326        |   39158.94
    6837      |     452  |        282        |   8846.80
    6821      |     408  |        291        |   48786.50
    6814      |     014  |        285        |   74159.76

最佳答案

这是你想要的吗?

   ORDER BY OutletId, Transactions desc

编辑:

如果我没理解错的话,您希望它按总交易量最多的商店排序。然后通过该组内的交易。为此,您需要在 outlet 级别再次汇总并返回结果:

select outor.*
from (SELECT up.outletid, up.revcode, count(up.receiptnumbe) as Transactions,
             sum(up.amount) as total
      FROM user_payment up
      WHERE date = (SELECT MAX(date) FROM user_payment)
      GROUP BY outletid, revcode
     ) outor join
     (SELECT up.outletid, count(up.receiptnumbe) as Transactions,
             sum(up.amount) as total
      FROM user_payment up
      WHERE date = (SELECT MAX(date) FROM user_payment)
      GROUP BY outletid
     ) o
     on outor.outletid = o.outletid
order by o.Transactions desc, outor.outletid, outor.Transactions desc;

关于mysql - 如何在sql中对2个不同的列进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21383847/

相关文章:

sql - Postgres : Create index on that text is null or not

mysql - SQL 查询语法错误 : unexpected 'SUM' (sum)

mysql - 在 mysql 中选择相似的值(有些东西,有些东西,有些东西,有些东西应该是一样的)

mysql - 将客户现有的 MS Access 数据库与其 Linux 托管站点集成?

php - 在 Laravel 中检查重复数据

php - MYSQL/PHP - 合并具有不同列的两个表

mysql - 创建一个新表,其中为另一个表中的每个元素创建一列

sql - 选择子查询 PostgreSQL

SQL Server 2005,语法错误

php - 从 MySQL 和 PDO (PHP) 填充 HTML; foreach 循环无法写入 MySQL 数据