sql server 2008 - How to do a group by and count individual group in sql subquery -
i have following table:
date_trans | customerid 2015-02-01 | 12 2015-02-01 | 14 2015-02-01 | 13 2015-02-01 | 12 2015-02-02 | 13 2015-02-02 | 12 2015-02-02 | 13 2015-02-02 | 14 2015-02-02 | 14
i able total transactions per day group by:
select date_trans, count(*) "transactions" thetable group date_trans date_trans | transactions 2015-02-01 | 4 2015-02-02 | 5
but not able partial numbers same date customers:
date_trans | transactions | "by 12" | "by 13" | "by 14" 2015-02-01 | 4 | 2 | 1 | 1 2015-02-02 | 5 | 1 | 2 | 2
i tried group in select not work.
how can achieve in sql 2014?
thank you
with trans ( select date_trans, count(*) "transactions" thetable group date_trans) , cust ( select customerid, date_trans, count(*) "cust_txns" thetable group customerid, date_trans) select c.date_trans, t.transactions, case when c.customerid = 12 cust_txns end "by 12", case when c.customerid = 13 cust_txns end "by 13", case when c.customerid = 14 cust_txns end "by 14" trans t join cust c on t.date_trans = c.date_trans
this 1 way it. however, if have many customers, have use dynamic sql.
edit: eliminate null values on rows, 1 more level of grouping needed below.
with trans ( select date_trans, count(*) "transactions" thetable group date_trans) , cust ( select customerid, date_trans, count(*) "cust_txns" thetable group customerid, date_trans) select c.date_trans, max(t.transactions) transactions, max(case when c.customerid = 12 cust_txns end) "by 12", max(case when c.customerid = 13 cust_txns end) "by 13", max(case when c.customerid = 14 cust_txns end) "by 14" trans t join cust c on t.date_trans = c.date_trans group c.date_trans
Comments
Post a Comment