Thursday, March 29, 2012

Count of matching result sets

I'm okay with simple select statements, but this one is kicking my behind...
I'm trying to create an overview of our data holdings for various
categories. It needs to be dynamic as the types of data and the accompanying
criteria will be dynamic.
The data holdings table, which I'll call "DH", is related via a one-to-many
to an "Xref_DH_Topic" table, which is related via a many-to-one to a "Topics"
table.
"DH" table:
| dhid | Name |
| 1 | Fred's Ocean Carbon Data |
| 2 | Joe's Tide Data |
| 3 | Pete's Surface Flux Data |
| 4 | Lou's Tide & Surface Flux Data |
"Xref_DH_Topic" table:
| xid | dhid | topicid |
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 1 |
| 4 | 2 | 3 |
| 5 | 3 | 1 |
| 6 | 3 | 4 |
| 7 | 3 | 5 |
| 8 | 4 | 1 |
| 9 | 4 | 3 |
| 10 | 4 | 4 |
| 11 | 4 | 5 |
"Topics" table:
| topicid | TopicTitle |
| 1 | Ocean |
| 2 | Carbon |
| 3 | Tide |
| 4 | Surface |
| 5 | Flux |
So far so good. Now I want to have a "DH Matrix" table which defines the
criteria for inclusion in a particular row, which will be modified as more
data holdings and topics are added. It is linked to an "Xref_Matrix_Topic"
table which links to the same "Topics" table as above.
"DH Matrix" table:
| dhmid | Category |
| 1 | All Ocean Data |
| 2 | Tide Data Holdings |
| 3 | Carbon Data Holdings |
| 4 | Surface Flux Data Holdings |
"Xref_Matrix_Topic" table:
| xmtid | dhmid | topicid |
| 1 | 1 | 1 |
| 2 | 2 | 1 |
| 3 | 2 | 3 |
| 4 | 3 | 1 |
| 5 | 3 | 2 |
| 6 | 4 | 1 |
| 7 | 4 | 4 |
| 8 | 4 | 5 |
The desired end-result is a view that will display each "category" in the
"DH Matrix" table and count up the number of rows in the "DH" table that
match the criteria set up in the "Xref_Matrix_Topic" table.
Matrix of Data Holdings:
| Category | # of Hits in DH |
| All Ocean Data | 4 |
| Tide Data Holdings | 2 |
| Carbon Data Holdings | 1 |
| Surface Flux Holdings | 2 |
Any help would be greatly appreciated.
TIA.
What about some DDL scripts and data for us ?

No comments:

Post a Comment