Each company
, has products and each product
has entries in detail1
, detail2
, detail3
table.
**Table Company**
cid | cname
-----+-----------
100 | Company 1
101 | Company 2
**Table Product**
pid | cid | dname
------+-----+-----------
1000 | 100 | Product A
2000 | 101 | Product B
**Table detail1**
pid | state | datetime
------+-------+----------------------------
1000 | A | 2013-06-03 11:49:49.224992
1000 | B | 2013-06-03 11:49:49.226124
1000 | B | 2013-06-03 11:49:49.228573
1000 | B | 2013-06-03 11:49:49.23136
1000 | A | 2013-06-03 11:49:49.233897
2000 | A | 2013-06-03 11:49:49.243572
2000 | B | 2013-06-03 11:49:49.245899
**Table detail2**
pid | type | datetime
------+------+----------------------------
1000 | T1 | 2013-06-03 11:49:49.257978
1000 | T1 | 2013-06-03 11:49:49.258865
1000 | T1 | 2013-06-03 11:49:49.261212
1000 | T1 | 2013-06-03 11:49:49.263515
2000 | T1 | 2013-06-03 11:49:49.270654
**Table detail3**
pid | quality | datetime
------+---------+----------------------------
1000 | Q1 | 2013-06-03 11:49:49.280894
1000 | Q1 | 2013-06-03 11:49:49.281786
1000 | Q1 | 2013-06-03 11:49:49.284011
2000 | Q1 | 2013-06-03 11:49:49.287797
2000 | Q1 | 2013-06-03 11:49:49.288629
2000 | Q1 | 2013-06-03 11:49:49.289587
I am looking for a query that would return data as follows:
CompanyID CompanyName detail1.StateA detail1.stateB count(detail2) count(detail3)
---------- ------------ --------------- --------------- -------------- ---------------
100 Company 1 2 3 4 3
101 Company 2 1 1 1 2
I might further restrict the result based on datetime
constraint.