Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join and count in SQL Server

Tags:

sql-server

I have two tables; let's call them TableA and TableB. Each element of TableB is associated with an element of TableA in a many-to-one relationship. Some elements of TableA may have no corresponding element in TableB.

I need to select every element in TableA, along with a column that will, for each row in the result set, contain the number of elements in TableB that are associated with that row in TableA, and that have a certain property.

Using MS SQL Server 2008 (Needs to also work in SQL Server 2005).

like image 645
Brennan Vincent Avatar asked Dec 28 '10 18:12

Brennan Vincent


People also ask

Can we use count and GROUP BY together?

The use of COUNT() function in conjunction with GROUP BY is useful for characterizing our data under various groupings. A combination of same values (on a column) will be treated as an individual group.

What is difference between count (*) and count () in SQL?

As you've already learned, COUNT(*) will count all the rows in the table, including NULL values. On the other hand, COUNT(column name) will count all the rows in the specified column while excluding NULL values. FROM orders; Do we get the same result?

What are the 4 types of joins in SQL?

Four types of joins: left, right, inner, and outer.

What are the 3 types of joins in SQL?

Different Types of SQL JOINs (INNER) JOIN : Returns records that have matching values in both tables. LEFT (OUTER) JOIN : Returns all records from the left table, and the matched records from the right table. RIGHT (OUTER) JOIN : Returns all records from the right table, and the matched records from the left table.


1 Answers

Updated

SELECT A.elementid, A.column1, A.column2, A.column3, 
       COUNT(CASE WHEN B.someColumn > 0 THEN B.elementid ELSE NULL END) Q
FROM TableA A
LEFT JOIN TableB B
ON A.elementid = B.elementid
GROUP BY A.elementid, A.column1, A.column2, A.column3
like image 134
Lamak Avatar answered Nov 03 '22 11:11

Lamak