在SQL中构建数据透视表:聚合排序

时间:2017-02-22 00:58:45

标签: mysql sql sql-server

我正在使用SQL(mysql)构建数据透视表,我想逐步完成这个问题,因此这个问题将成为尝试构建越来越复杂的数据透视表的系列文章的一部分在SQL中。

我有以下架构给出标题:

  • 提供商
  • 标题
  • 收入

我想构建一个按提供者和标题分组的聚合,如下所示:

provider    title      revenue
Sony        titanic    9.99
Paramount   T2         14.99
Sony        star wars  12.99

这很简单,我们可以通过以下方式汇总:

SELECT provider, title, SUM(revenue) FROM table GROUP BY provider, title

接下来我要做的是首先按提供商的收入总和,然后按字母顺序按标题对提供商进行排序。例如,以上内容应按以下方式排序:

[-] Sony (12.99+9.99 = 22.98)
    - star wars (A-Z)
    - titanic (A-Z)
[-] Paramount (9.99)
    - T2

我如何在SQL中进行聚合?这是一个带有示例数据的小提琴:http://sqlfiddle.com/#!9/a9b5d9/2

2 个答案:

答案 0 :(得分:2)

\n

enter image description here

无法打开您的SQLfiddle,我将您的SQL复制到我的本地站点,结果如下:

enter image description here

答案 1 :(得分:1)

您需要的只是查询的with rollup子句:

select provider, title, sum(customer_price) revenue from `100`
group by provider, title
with rollup

'总计'行将在提供者和标题列中具有NULL(最后一行是Grand Total行),如下所示:

|               provider |                      title | revenue |
|------------------------|----------------------------|---------|
|             DISTRIBBER |                Finding Joe |   16.99 |
|             DISTRIBBER |                     (null) |   16.99 |
|            Echo Bridge |               Do Something |    1.99 |
|            Echo Bridge |                 Down in LA |       0 |
|            Echo Bridge | The L.A. Complex, Season 1 |   19.99 |
|            Echo Bridge | The Other Side of the Door |    6.97 |
|            Echo Bridge |               Who You Know |    3.98 |
|            Echo Bridge |                     (null) |   32.93 |
| Electric Entertainment |         Leverage, Season 4 |   31.99 |
| Electric Entertainment |     The Cross My Heart Job |    2.99 |
| Electric Entertainment |             The Inside Job |    1.99 |
| Electric Entertainment |              The Radio Job |    1.99 |
| Electric Entertainment |       The Scheherazade Job |    2.99 |
| Electric Entertainment |                     (null) |   41.95 |
|               HALLMARK |      The Good Witch's Gift |    3.99 |
|               HALLMARK |                     (null) |    3.99 |
|            Quebec Inc. |        2 Frogs In the West |    5.99 |
|            Quebec Inc. |                     (null) |    5.99 |
|                 VIRGIL |         One Lucky Elephant |    3.99 |
|                 VIRGIL |                     (null) |    3.99 |
|                 (null) |                     (null) |  105.84 |

SQL Fiddle