Question

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
field2 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

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top