i need a complex query:
Consider this table:
ID - field1 - field2
=================
1 a 10
2 a 10
3 a 20
4 b 20
i need a query that counts the total record grouped by field1 and field2. I mean i need this result:
field - count
==================
field1 a - 3
field1 b - 1
field2 10 - 2
fiel开发者_如何学JAVAd2 20 - 2
maybe i need to do 2 query for each field i need the count?
SELECT field1, COUNT( * ) FROM t1 GROUP BY field1
?
Thanks for any suggestions
You do need two SELECTs, but you can get them to return a single result set as follows. Note that you need to CAST the first SELECT so that the values are compatible with the text field in the second 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
精彩评论