MySQL:在同一列中按值查询和分组

时间:2014-07-09 09:24:22

标签: mysql count group-by

我有一个sql表数据如下。

c_type_id | s_id | value
     1    | 11   | Winx32
     1    | 12   | Domain1
     2    | 11   | Winx64
     2    | 12   | Domain2
     3    | 11   | Winx32
     3    | 12   | Domain1
     4    | 11   | Winx32
     4    | 12   | Domain2

如何查询和分组以获得以下结果。?

countall | platform | domain
       2 | Winx32   | Domain1
       1 | Winx64   | Domain2
       1 | Winx32   | Domain2

3 个答案:

答案 0 :(得分:1)

您需要透视表格以在单独的列中获取平台和域,然后您可以使用COUNTGROUP BY

SELECT COUNT(*) AS countall, platform, domain
FROM (SELECT MAX(CASE WHEN s_id = 11 THEN value END) AS platform,
             MAX(CASE WHEN s_id = 12 THEN value END) AS domain
      FROM YourTable
      GROUP BY c_type_id) AS pivoted
GROUP BY platform, domain

答案 1 :(得分:0)

SELECT  COUNT(*) countall,
        p.value platform,
        d.value domain
FROM    mytable p
JOIN    mytable d
ON      (d.c_type_id, d.s_id) = (p.c_type_id, 12)
WHERE   p.s_id = 11
GROUP BY
        d.c_type_id

答案 2 :(得分:0)

假设您的表名是'test1',这将是您的解决方案:

SELECT COUNT(*) AS countall, t1a.value AS platform, t1b.value AS domain
FROM test1 AS t1a
LEFT JOIN test1 AS t1b
       ON t1b.c_type_id = t1a.c_type_id
WHERE t1a.s_id = 11
  AND t1b.s_id = 12
GROUP BY t1a.value, t1b.value

在MySQL服务器v5.5.37上测试

祝你好运, speedbomb