【问题标题】:How to do a group by and count individual group in sql subquery如何在sql子查询中进行分组并计算单个组
【发布时间】:2015-08-19 15:13:46
【问题描述】:

我有下表:

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 中实现这一点?

谢谢

【问题讨论】:

  • 如果没有“动态 sql”(编写 sql 的代码),您无法仅仅因为您的数据发生更改而获得不同数量的列。你可以做你所描述的事情,只要你总是并且曾经想要为这三个特定客户 透视数据吗?或者,每个客户每天一行的结果集怎么样? (列名为date_trans, customerId, transaction_count?)
  • 案例其实是静态客户,能动态做这个就好了。通过将 customer_id 添加到 GROUP BY 子句,可以实现每个客户每天一行的结果集。

标签: sql sql-server-2008


【解决方案1】:
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

【讨论】:

  • 很好的答案,但是,它每天给我 3 行,数据不会每天合并成一行。正确的结果在那里,但其他列是 NULL
猜你喜欢
  • 1970-01-01
  • 2012-12-31
  • 1970-01-01
  • 1970-01-01
  • 2015-06-23
  • 1970-01-01
  • 1970-01-01
  • 2019-09-08
  • 1970-01-01
相关资源
最近更新 更多