Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL SELECT with GROUP BY id

I have table with 'People'

Columns

  • ID
  • Name
  • Age

And table with 'Notes':

Columns

  • ID
  • Text
  • FK_Author

I want to select count of notes for all authors from people table and their name and age, but I want to group it by PERSON ID, not name. There are many situations when people have same name, but ID is obviously always different.

EXAMPLE (input)

PEOPLE:

╔════╦═══════╦═════╗
║ ID ║ NAME  ║ AGE ║
╠════╬═══════╬═════╣
║  1 ║ John  ║  12 ║
║  2 ║ Annie ║  29 ║
║  3 ║ John  ║  44 ║
╚════╩═══════╩═════╝

NOTES:

╔════╦═══════╦═══════════╗
║ ID ║ TEXT  ║ FK_AUTHOR ║
╠════╬═══════╬═══════════╣
║  1 ║ 'aaa' ║         1 ║
║  2 ║ 'aaa' ║         1 ║
║  3 ║ 'aaa' ║         2 ║
║  4 ║ 'aaa' ║         2 ║
║  5 ║ 'aaa' ║         3 ║
╚════╩═══════╩═══════════╝

Expected result:

╔═══════╦═════╦════════════╗
║ NAME  ║ AGE ║ TOTALCOUNT ║
╠═══════╬═════╬════════════╣
║ John  ║  12 ║          2 ║
║ Annie ║  29 ║          2 ║
║ John  ║  44 ║          1 ║
╚═══════╩═════╩════════════╝

When I select data I have to group by Name too if I want to select this column because if I dont, I get error.

like image 556
Ellbar Avatar asked Apr 03 '13 11:04

Ellbar


People also ask

Can we use SELECT * with GROUP BY?

You cannot write select inside the Group by clause.

Can we use WHERE clause with GROUP BY?

GROUP BY Clause is utilized with the SELECT statement. GROUP BY aggregates the results on the basis of selected column: COUNT, MAX, MIN, SUM, AVG, etc. GROUP BY returns only one result per group of data. GROUP BY Clause always follows the WHERE Clause.

What is grouping ID in SQL?

GROUPING_ID() is used to create a value for each row in the Title column that identifies its level of aggregation. SQL Copy.

How do you use GROUP BY and ORDER BY together?

When combining the Group By and Order By clauses, it is important to bear in mind that, in terms of placement within a SELECT statement: The GROUP BY clause is placed after the WHERE clause. The GROUP BY clause is placed before the ORDER BY clause.


1 Answers

Since you want to get all records from table People, you need to join it with Notes by using LEFT JOIN so any user without any record on Notes will be included in the list with thev value of totalCount with zero.

SELECT  a.ID, a.Name, a.Age,
        COUNT(b.FK_Author) totalCount
FROM    People a
        LEFT JOIN Notes b
            ON a.ID = b.FK_Author
GROUP   BY a.ID, a.Name, a.Age
  • SQLFiddle Demo

To further gain more knowledge about joins, kindly visit the link below:

  • Visual Representation of SQL Joins

OUTPUT

╔════╦═══════╦═════╦════════════╗
║ ID ║ NAME  ║ AGE ║ TOTALCOUNT ║
╠════╬═══════╬═════╬════════════╣
║  1 ║ John  ║  12 ║          2 ║
║  2 ║ Annie ║  29 ║          2 ║
║  3 ║ John  ║  44 ║          1 ║
╚════╩═══════╩═════╩════════════╝
like image 143
John Woo Avatar answered Sep 22 '22 08:09

John Woo