如何在sql子查询中进行分组并计算单个组

时间:2015-08-19 15:13:46

标签: sql sql-server-2008

我有下表:

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

我可以通过GROUP BY获得每日总交易次数:

SELECT date_trans, COUNT(*) as "Transactions" FROM theTable GROUP BY date_trans

date_trans | Transactions
2015-02-01 | 4
2015-02-02 | 5

但是我无法从同一天获得客户的部分号码:

date_trans | Transactions | "By 12" | "By 13" | "By 14"
2015-02-01 | 4            | 2       | 1       | 1
2015-02-02 | 5            | 1       | 2       | 2

我尝试在选择中进行分组,但它不起作用。

我如何在SQL 2014中实现这一目标?

谢谢

1 个答案:

答案 0 :(得分:3)

with trans as (
SELECT date_trans, COUNT(*) as "Transactions" 
FROM theTable
GROUP BY date_trans)
, cust as (
SELECT customerid, date_trans, COUNT(*) as "cust_txns" 
FROM theTable
GROUP BY customerid, date_trans)
select c.date_trans,
       t.transactions,
       case when c.customerid = 12 then cust_txns end as "By 12",
       case when c.customerid = 13 then cust_txns end as "By 13",
       case when c.customerid = 14 then cust_txns end as "By 14"   
from trans t join cust c
on t.date_trans = c.date_trans

这是一种方法。但是,如果您有许多客户,则必须使用动态SQL。

编辑:要消除行上的空值,需要再进行一次分组,如下所示。

with trans as (
SELECT date_trans, COUNT(*) as "Transactions" 
FROM thetable
GROUP BY date_trans)
, cust as (
SELECT customerid, date_trans, COUNT(*) as "cust_txns" 
FROM thetable
GROUP BY customerid, date_trans)
select c.date_trans,
       max(t.transactions) as transactions,
       max(case when c.customerid = 12 then cust_txns end) as "By 12",
       max(case when c.customerid = 13 then cust_txns end) as "By 13",
       max(case when c.customerid = 14 then cust_txns end) as "By 14"   
from trans t join cust c
on t.date_trans = c.date_trans
group by c.date_trans

SQL Fiddle