SQL多个组 - 有可能吗?

时间:2010-11-16 23:22:31

标签: sql

我对此表单有疑问:

SELECT e.date, SUM(e.size) as bytes
FROM entries AS e
GROUP BY e.date
ORDER BY bytes DESC

我有一个名为client的列,它由静态值(0,1,2,3)组成,所以我想得到这个:

SELECT e.date, SUM(e.size) as bytes
FROM entries AS e
WHERE e.client = 0
GROUP BY e.date
ORDER BY bytes DESC

为每个客户端类型重复但在单个查询中为每个客户端类型获取汇总大小的结果:

   DATE    | CLI0-SIZE | CLI1-SIZE | CLI2-SIZE | CLI3-SIZE
2010-11-11      113         344         435         155

2 个答案:

答案 0 :(得分:7)

你可以试试这个

SELECT e.date,
    SUM(CASE WHEN e.client = 0 THEN e.size ELSE 0 END) as CLI0-SIZE,
    SUM(CASE WHEN e.client = 1 THEN e.size ELSE 0 END) as CLI1-SIZE,
    SUM(CASE WHEN e.client = 2 THEN e.size ELSE 0 END) as CLI2-SIZE,
    SUM(CASE WHEN e.client = 3 THEN e.size ELSE 0 END) as CLI3-SIZE
FROM entries AS e
GROUP BY e.date

答案 1 :(得分:1)

RDMS:Microsoft SQL Server

这将返回以下布局:

   date    | client | bytes
2010-11-11 |   2    |  435
2010-11-11 |   1    |  344
2010-11-11 |   3    |  155
2010-11-11 |   0    |  113

这将按所有客户类型进行分组,而不仅仅是0,1,2,3 - 我假设你想要这个。

SELECT
    e.date,
    e.client,
    SUM(e.size) AS bytes
FROM
    entries AS e
GROUP BY
    e.date,
    e.client
ORDER BY
    bytes DESC

然后,您可以在桌面上执行数据透视。