简体   繁体   中英

SQL counting total rows with distinct?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM