简体   繁体   中英

Sql count distinct values

I am trying to count distinct values grouped by different column this is my table: product

id typePr namePr
1 typeA nameA
2 typeeB nameC
3 typeA nameB
4 typeA nameB
5 typeB nameA
6 typeB nameC
7 typeC nameB

I wanna get something like this:

[{"typePr":"typeA","nameA":"1","nameB":"2"}, {"typePr":"typeB","nameC":"2","nameA":"1"}, {"typePr":"typeC","nameB":"1"} ]

is there any possibility to do this?

The general query you want here uses GROUP BY :

SELECT age, SUM(gender = 'F') AS countF, SUM(gender = 'H') AS countH
FROM yourTable
GROUP BY age;

As for turning your result set into JSON, you could try to do this from MySQL, but more typically you would handle this from your presentation layer (eg PHP).

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