Please help me with the following situation:
In SQL Server 2008 I have a database with the tables:
- Installations (
id, name) which is unique for a given system - Products (
Id, name) which are installed on a system
And because a system has more products and the same product can be installed on multiple machines there is InstallationXProduct table withe their ids.
Another table Usages (usageid, productid, date etc) is linked to a product to keep track of product usages.
I need a script to link Installation, Products and Usage count for each Installation-Product pair, e.g.
Installation 1 Product A 2
Installation 1 Product B 3
Installation 2 Product A 1
Installation 2 Product C 2
Thank you for any help
Later EDIT:
Tables:
Installation:InstallationID, InstallationNameProduct:ProductID, ProductNameInstallationXProduct:InstallationID, ProductIDUsage:UsageID, DateRecorded, ProductID
Set up data:
Insert into Installation values(1,'A')
Insert into Installation values(2,'B')
Insert into Product values (1,'P1')
Insert into Product values (2,'P2')
Insert into InstallationXProduct values (1,1)
Insert into InstallationXProduct values (2,1)
Insert into InstallationXProduct values (1,2)
Insert into InstallationXProduct values (2,2)
Insert into Usage values(1,getdate(),1)
Insert into Usage values(2,getdate(),2)
Insert into Usage values(3,getdate(),1)
Query to select:
select I.InstallationID, P.ProductID, count(U.UsageID)
from Installation I
join InstallationXProduct IXC on I.InstallationID = IXC.InstallationID
join Product P on P.ProductID = IXC.ProductID
join Usage U on U.ProductID = P.ProductID
group by I.InstallationId,P.ProductID
returns:
1 1 2
2 1 2
1 2 1
2 2 1
After reading this light version I think I understand why it is not possible to split the usages in products and installations, there is no way I can tell whether usage one was recorded on product 1 from installation 1 or 2.
If you need to count the rows in
Usages, then something like this might be of help: