![]() |
|
SQL Grouping |
ngiacomelli
Member #5,114
October 2004
|
Just another general SQL question regarding grouping. Basically, I'm pulling 25 rows from a table, and would like to group rows by a particular field (we'll call it field1). I'd do something like this: SELECT *, COUNT(row_id) AS total FROM table GROUP BY field1 LIMIT 25 This nicely clumps together the rows that share the same value in field1, leaving the total variable to signify how many rows have been grouped. However, what I'm looking to do is as follows: field1 | field2 ----------------------- corn | pizza hotdog | cow corn | man The above query will take this result set and will group row 1 and 3 because they both share an identical value for field1. It will also return row 2. What's the best way to also grab each of the grouped rows other values? So effectively, if more than one row is found with an identical field1 value, I'd like to be able to say: Two rows had a value of corn in field1. These two rows had the following values for field2: pizza, man. What's the best way to handle this?
|
Archon
Member #4,195
January 2004
![]() |
Quote: What's the best way to handle this? An embedded SQL select query when doing the WHERE clause. |
ngiacomelli
Member #5,114
October 2004
|
I have absolutely no concept of that. Any good online resources?
|
Matthew Leverton
Supreme Loser
January 1999
![]() |
Perhaps: SELECT field1, GROUP_CONCAT(field2), COUNT(*) FROM foo GROUP BY field1 |
bamccaig
Member #7,536
July 2006
![]() |
Or two queries if you need the individual values... -- acc.js | al4anim - Allegro 4 Animation library | Allegro 5 VS/NuGet Guide | Allegro.cc Mockup | Allegro.cc <code> Tag | Allegro 4 Timer Example (w/ Semaphores) | Allegro 5 "Winpkg" (MSVC readme) | Bambot | Blog | C++ STL Container Flowchart | Castopulence Software | Check Return Values | Derail? | Is This A Discussion? Flow Chart | Filesystem Hierarchy Standard | Clean Code Talks - Global State and Singletons | How To Use Header Files | GNU/Linux (Debian, Fedora, Gentoo) | rot (rot13, rot47, rotN) | Streaming |
|