views:

39

answers:

1

This is not a homework question, just something at work that's bugging me.

I'm trying to write a query against these tables below. The two tables, history and code are joined to the historyassignment table by the historyid and codeid columns.

Table: HistoryAssignment

| AssignmentID | HistoryID | CodeID |
|--------------|-----------|--------|
| 1            | 100       | 200    |
|--------------|-----------|--------|
| 2            | 101       | 201    |
|--------------|-----------|--------|
| 3            | 102       | 202    |
|--------------|-----------|--------|

Table: Code 

| CodeID | Desc |
|--------|------|
| 200    | ABC  |
|--------|------|
| 201    | DEF  |
|--------|------|
| 202    | GHI  |
|--------|------|

Table: History

| HistoryID | Desc | HistDate |
|-----------|------|----------|
| 100       | JKL  | 5/1/2010 |
|-----------|------|----------|
| 101       | MNO  | 7/1/2009 |
|-----------|------|----------|
| 102       | PQR  | 7/9/2010 |
|-----------|------|----------|
| 103       | STU  | 6/2/2010 |
|-----------|------|----------|
| 104       | VWX  | 5/7/2010 |
|-----------|------|----------|
| 105       | YZ   | 2/5/2010 |
|-----------|------|----------|

My goal is to get a count of total number of history IDs that are mapped in the historyassigment table and the total number of history IDs there are in the history table. The results should be grouped the month and year of the histdate column in the history table. Like below.

Year    Month   Total   Mapped
2009    7   1   1
2010    2   1   0
2010    5   2   1
2010    6   1   0
2010    7   1   1

Any assistance would be greatly appreciated.

+1  A: 
SELECT   YEAR(HistDate) [Year]      ,
         MONTH(HistDate) [Month]    ,
         COUNT(h.HistoryID) [Total] ,
         COUNT(DISTINCT ha.HistoryID) [Mapped]
FROM     History h
         LEFT OUTER JOIN HistoryAssignment ha
         ON       ha.HistoryID = h.HistoryID
GROUP BY YEAR(HistDate),
         MONTH(HistDate)
ORDER BY YEAR(HistDate),
         MONTH(HistDate)
Martin Smith