mysql query to dynamically convert row data to columns

前端 未结 4 1439
广开言路
广开言路 2020-12-10 08:54

I am working on a pivot table query. The schema is as follows

Sno, Name, District

The same name may appear in many districts eg take the sample data for exam

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-10 09:21

    The following assumes you want matches of distinct (name/district) pairs. I.e. Luke/CA and Duke/CA would yield two results:

    SELECT name, District, count(District) AS count
    FROM district_details
    GROUP BY District, name
    

    If this is not the case simply remove name from the GROUP BY clause.

    Lastly, notice that I switched sum() for count() as you are trying to count all of the grouped rows rather than getting a summation of values.

提交回复
热议问题