mysql查询嵌套查询双排序

时间:2016-01-04 10:18:10

标签: mysql nested-queries

我使用简单的SQL查询,如下所示:$sql="SELECT name, DATE_FORMAT(date_add,'%d-%m-%Y') as mydate, payment FROM atable"我在前面得到3列表:

name  mydate     payment
luke  10-12-2015  50
tom   13-12-2015  60
john  13-12-2015  40
tom   14-12-2015  30
eva   15-12-2015  40
john  16-12-2015  70
tom   16-12-2015  20

是否有可能编写sql查询(我想可能以某种方式嵌套),这样我首先要按名称获得每个组的付款总额,然后按总和对DESC进行排序,但最终表格如下:

name  mydate     payment
john  13-12-2015  40
john  16-12-2015  70
tom   13-12-2015  60
tom   14-12-2015  30
tom   16-12-2015  20
luke  10-12-2015  50
eva   15-12-2015  40
约翰首先是因为他的支付金额是110,与汤姆的支付金额相同,但他首先按字母顺序排列,然后是卢克和伊娃。查询的外观如何(如果可能在一个SQL查询中执行所有步骤)?

3 个答案:

答案 0 :(得分:2)

这是一种方式:SQL Fiddle

MySQL 5.6架构设置

CREATE TABLE atable
    (`name` varchar(4), `mydate` datetime, `payment` int)
;

INSERT INTO atable
    (`name`, `mydate`, `payment`)
VALUES
    ('luke', '2015-12-10 00:00:00', 50),
    ('tom', '2015-12-13 00:00:00', 60),
    ('john', '2015-12-13 00:00:00', 40),
    ('tom', '2015-12-14 00:00:00', 30),
    ('eva', '2015-12-15 00:00:00', 40),
    ('john', '2015-12-16 00:00:00', 70),
    ('tom', '2015-12-16 00:00:00', 20)
;

查询1

select
      atable.name
    , atable.mydate
    , atable.payment
    , g.sum_payment
from atable
inner join (
            select name, sum(payment) as sum_payment
            from atable
            group by name
           ) g on atable.name = g.name
order by
      g.sum_payment DESC
    , atable.name
    , atable.mydate
    , atable.payment

<强> Results

| name |                     mydate | payment | sum_payment |
|------|----------------------------|---------|-------------|
| john | December, 13 2015 00:00:00 |      40 |         110 |
| john | December, 16 2015 00:00:00 |      70 |         110 |
|  tom | December, 13 2015 00:00:00 |      60 |         110 |
|  tom | December, 14 2015 00:00:00 |      30 |         110 |
|  tom | December, 16 2015 00:00:00 |      20 |         110 |
| luke | December, 10 2015 00:00:00 |      50 |          50 |
|  eva | December, 15 2015 00:00:00 |      40 |          40 |

答案 1 :(得分:0)

$sql="SELECT name, DATE_FORMAT(date_add,'%d-%m-%Y') as mydate, payment FROM atable group by name order by payment DESC"

答案 2 :(得分:0)

$sql="SELECT name, DATE_FORMAT(date_add,'%d-%m-%Y') as mydate, sum(payment) as total FROM atable group by name order by total DESC"

我们需要根据您的要求进行总结和分组。