开发者

SQL counting total rows with distinct?

开发者 https://www.devze.com 2023-02-03 10:22 出处:网络
i need a complex query: Consider this table: ID - field1 - field2 ================= 1a10 2a10 3a20 4b20

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
0

精彩评论

暂无评论...
验证码 换一张
取 消