SQL计算总行数与不同?

时间:2011-01-11 14:34:39

标签: sql mysql group-by distinct

我需要一个复杂的查询:

考虑下表:

ID - field1 - field2
 =================
 1     a        10
 2     a        10
 3     a        20
 4     b        20

我需要一个查询来计算按field1和field2分组的总记录数。我的意思是我需要这个结果:

field      - count
==================
field1 a   - 3
field1 b   - 1
field2 10  - 2
field2 20  - 2

也许我需要对每个需要计数的字段进行2次查询?

 SELECT field1, COUNT( * ) FROM t1 GROUP BY field1

感谢您的任何建议

1 个答案:

答案 0 :(得分:2)

您确实需要两个SELECT,但您可以让它们返回单个结果集,如下所示。请注意,您需要CAST第一个SELECT,以便值与第二个SELECT中的文本字段兼容:

 SELECT 'field1' AS FieldName, CAST(field1 AS CHAR) AS FieldValue, COUNT(*) AS Count 
   FROM table GROUP BY field1
 UNION ALL 
 SELECT 'field2' AS FieldName, field2 AS FieldValue, COUNT(*) AS Count 
   FROM table GROUP BY field2