按水平展示分组和排序

时间:2014-06-23 15:04:12

标签: mysql group-by

我有一个SQL语句如下:

SELECT
    ID,
    fld01, 
    fld02,
    fld03 AS AGENT,
    fld04 AS DIGIT,
    COUNT(*) AS fld05 AS OCCURRENCE
FROM table AS BaseView
GROUP BY fld03
ORDER BY fld03, fld05  DESC, fld04

我的返回结果总是10行,从0到9(对于按fld03分组的返回结果),计数(*)作为返回结果的出现次数。

因此,我的返回结果应始终如下:

fld01 | fld02 | fld03 (AGENT) | fld04 (DIGIT) | fld05 (OCCURRENCE)

XX    | YY    | AGENT1        | 0             | 16
XX    | YY    | AGENT1        | 4             | 15
XX    | YY    | AGENT1        | 6             | 12
XX    | YY    | AGENT1        | 7             | 10
XX    | YY    | AGENT1        | 1             | 9
XX    | YY    | AGENT1        | 9             | 9
XX    | YY    | AGENT1        | 3             | 8
XX    | YY    | AGENT1        | 5             | 7
XX    | YY    | AGENT1        | 2             | 4
XX    | YY    | AGENT1        | 8             | 2

我的问题是:

我希望我的返回结果显示为水平显示(按DESC模式中的计数数量排序)。

预期返回的结果如下:

fld01 | fld02 | fld03  | D01 | D02 | D03 | D04 | D05 | D06 | D07 | D08 | D09 | D10

XX    | YY    | AGENT1 | 0   | 4   | 6   | 7   | 1   | 9   | 3   | 5   | 2   | 8 

请告知。

1 个答案:

答案 0 :(得分:0)

首先,它看起来像fld01和fld02,对于fld03的所有值都是相同的,所以实际上它们应该在一个单独的表中。您将表标记为BaseView,因此可能已经是这种情况。请注意,以下示例查询假定上述内容为真(fld01,fld02和fld03对于fld03的每个值始终相同)

另外这感觉很讨厌 - 这实际上是输出的工作,而不是这个数据选择阶段。我不会在我的系统中以这种方式做事。

SELECT
    -- base values
    baseView.ID,
    baseView.fld01,
    baseView.fld02,
    baseView.fld03,

    -- counts from the various tables
    COALESCE(COUNT(d01.fld03),0) AS d01,
    COALESCE(COUNT(d02.fld03),0) AS d02,
    COALESCE(COUNT(d03.fld03),0) AS d03,
    COALESCE(COUNT(d04.fld03),0) AS d04,
    COALESCE(COUNT(d05.fld03),0) AS d05,
    COALESCE(COUNT(d06.fld03),0) AS d06,
    COALESCE(COUNT(d07.fld03),0) AS d07,
    COALESCE(COUNT(d08.fld03),0) AS d08,
    COALESCE(COUNT(d09.fld03),0) AS d09,
    COALESCE(COUNT(d10.fld03),0) AS d10

FROM table AS baseView
LEFT JOIN table AS d01
    ON d01.fld03 = baseView.fld03
    AND d01.fld04 = 1
LEFT JOIN table AS d02
    ON d02.fld03 = baseView.fld03
    AND d02.fld04 = 2
LEFT JOIN table AS d03
    ON d03.fld03 = baseView.fld03
    AND d03.fld04 = 3
LEFT JOIN table AS d04
    ON d04.fld03 = baseView.fld03
    AND d04.fld04 = 4
LEFT JOIN table AS d05
    ON d05.fld03 = baseView.fld03
    AND d05.fld04 = 5
LEFT JOIN table AS d06
    ON d06.fld03 = baseView.fld03
    AND d06.fld04 = 6
LEFT JOIN table AS d07
    ON d07.fld03 = baseView.fld03
    AND d07.fld04 = 7
LEFT JOIN table AS d08
    ON d08.fld03 = baseView.fld03
    AND d08.fld04 = 8
LEFT JOIN table AS d09
    ON d09.fld03 = baseView.fld03
    AND d09.fld04 = 9
LEFT JOIN table AS d10
    ON d10.fld03 = baseView.fld03
    AND d10.fld04 = 0

GROUP BY baseView.fld03
ORDER BY fld03