I have 2 tables
tbltraining
trId(PK) trname
------- ------
1 training1
2 training2
3 training3
4 training4
5 training5
6 training6
tbltrainAssign
trassigno trId(FK) date1 date2
--------- ------ ----------- ----------
1 1 12/12/2012 12/12/2013
1 1 12/12/2012 12/12/2013
2 3 01/12/2012 08/12/2013
2 3 01/12/2012 08/12/2013
2 3 01/12/2012 08/12/2013
3 1 02/12/2012 12/12/2013
3 1 12/12/2012 12/12/2013
what i want is the data from tbltraining with the count of assignments. trId =1 is assigned 2 times and trId is assigned 1tim in tbltrainAssign . so the result should look like
trId trName count
1 training1 2
2 training2 0
3 training3 1
4 training4 0
5 training5 0
6 training6 0
What you need is a simple, straightforward,
JOINespeciallyLEFT JOINto get unmatchedtrNames that had no assignment in the second table, withCOUNTand aGROUP BYlike so:SQL Fiddle Demo
Side not: Please avoid descriptive prefixes that you are using in the tables’ names and the columns’ names the
tbland thetr.Update: You have to select the distinct dates from the assignment table in order to count the distinct assignments for each training like so:
Updated SQL Fiddle Demo