简体   繁体   中英

group distinct rows and counting repeats

I am very new to SQL and I would like to create a sql function (or statement) that groups my transaction table based on firstname and lastname , while counting the number of repeats and the id.

transaction has the following columns: id , firstname , lastname etc..

I would like my return results look something like this in Json:

[{
    firstname:'John',
    lastname:'Doe',
    transaction_num:6,
    transaction_ids:[1,3,56,78,88,90]
},{
    firstname:'Jane',
    lastname:'Smith',
    transaction_num:2,
    transaction_ids:[8,9]
}]

Is there a way to do it in sql?

SELECT firstname,lastname,GROUP_CONCAT(id) transaction_ids,COUNT(*) transaction_num FROM t GROUP BY firstname,lastname

根据Mihai的建议,完美的答案!

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