简体   繁体   中英

categorize by groupby-SQL

I have a table called list_details

listId     tier
1           5
1           5   
1           6   
2           4
2           5

I want the following result:

listId      tier    
1           5(2), 6(1)
2           4(1),5(1)

I tried the following query:

SELECT ld.listId,count(ld.tier)
from list_details ld
group by ld.listId

and it gives me :

listId      tier    
1           3
2           2

But I dont know how I can put the condition or... to categorize based on the tiers.

Any help is appreciated

Thanks Mike:

Your query result is:

ListId      tierData
1            5(2), 6(1), 4(1),5(1)

But I want:

listId      tier    
1           5(2), 6(1)
2           4(1),5(1)

I am assuming that you don;t really need the response in the format of 5(2), 6(1) or if you did need that format for display, you could provide that format in teh application layer.

You should simply add multiple groupings:

SELECT
   listId,
   tier,
   COUNT(1) AS `tierCount`
FROM list_details
GROUP BY listId, tier
ORDER BY listId ASC, tier ASC

If you need that EXACT text result, you can do something like this:

SELECT
    a.listID AS listID,
    GROUP_CONCAT(
        CONCAT(
            a.tier,
            '(',
            a.tierCount,
            ')'
        )
    ) AS tierData
FROM (
    SELECT
       listId,
       tier,
       COUNT(1) AS `tierCount`
    FROM list_details
    GROUP BY listId, tier
) AS a
GROUP BY listID
ORDER BY listID ASC
SELECT ld.listId, ld.tier, count(ld.tier) 
FROM list_details ld 
GROUP by ld.listId, ld.tier;

Will yield:

list_id tier count
1  5  2
1  6  1

etc

You want to GROUP BY both listid and tier .

SELECT 
    ld.listId,
    ld.tier,
    count(ld.tier)
FROM list_details ld
GROUP BY ld.listId, ld.tier

This will result in:

listId    tier    count
1         5       2
1         6       1
2         4       1
2         5       1

That isn't your desired output 100%, but it's close. To get your desired output will require some funky SQL, or to display the result like that in your UI.

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