postgresql - Join mutiple tables with date -
i have 3 tables
**table a** +-----------------+ | name | id | +------------------ | a1 | 1 | | a2 | 2 | | a3 | 3 | +------------------ **table b** +---------------------------------------+-----+-------+ | timestamp | type| id | +---------------------------------------+-----+-------+ | 2013-05-10 08:10:10.161302-04 | b1 | 1 | | 2013-05-10 09:20:10.171302-04 | b1 | 1 | | 2013-05-12 08:10:10.161302-04 | b2 | 3 | | 2013-05-13 08:10:10.161302-04 | b2 | 3 | | 2013-05-14 08:10:10.161302-04 | b1 | 2 | +---------------------------------------+------+------+ **table c** +---------------------------------------+-----+-------+ | timestamp | type| id | +---------------------------------------+-----+-------+ | 2013-05-12 08:10:10.161302-04 | c1 | 1 | | 2013-05-12 09:20:10.171302-04 | c2 | 2 | | 2013-05-12 08:10:10.161302-04 | c1 | 2 | | 2013-05-12 08:10:10.161302-04 | c3 | 1 | | 2013-05-13 08:10:10.161302-04 | c1 | 2 | | 2013-05-13 08:10:10.161302-04 | c3 | 3 | | 2013-05-14 08:10:10.161302-04 | c1 | 1 | +---------------------------------------+------+------+- **expected result of query** +---------------------------------------+-----------------------------+ | date | b.count(b1 entries) | c.count(c1 entries) | +---------------------+-----------------------+-----------------------+ | 2013-05-10 | 2 | 0 | | 2013-05-12 | 0 | 2 | | 2013-05-13 | 0 | 1 | | 2013-05-14 | 1 | 1 | +---------------------+-----------------------+-----------------------+
- the id in table b , table c refer table a.id
- the query looking : for each day count number of b1 entries in table b , number of c1 entries in table c ids {1,2}
any suggestions welcome.
try query
select case when b.dtpart null a.dtpart else b.dtpart end dtpart, case when a.cnt null 0 else a.cnt end acnt, case when b.cnt null 0 else b.cnt end bcnt (select date_trunc('day', "timestamp" ) dtpart, count(*) cnt tbl1 "id" in (1,2) group date_trunc('day', "timestamp" )) full join (select date_trunc('day', "timestamp" ) dtpart, count(*) cnt tbl2 "id" in (1,2) group date_trunc('day', "timestamp" )) b on a.dtpart=b.dtpart
sql fiddle:
| dtpart | acnt | bcnt | -------------------------------------------- | may, 14 2013 00:00:00+0000 | 1 | 1 | | may, 10 2013 00:00:00+0000 | 2 | 0 | | may, 13 2013 00:00:00+0000 | 0 | 1 | | may, 12 2013 00:00:00+0000 | 0 | 4 |
Comments
Post a Comment