SQL:如何将数据分组到波段

时间:2015-10-16 14:15:43

标签: sql grouping

我创建了一个查询,显示了单个客户在事务列表中出现的次数....

select Client_Ref, count(*)
from Transactions
where Start_Date >= '2015-01-01'
group by Client_Ref
order by Client_Ref

...这会返回这样的数据......

Client1   1
Client2   4
Client3   1
Client4   3

..我需要做的是将其总结为频率带,以便我得到这样的东西......

No. of Clients with 1 transaction   53
No. of Clients with 2 transaction   157
No. of Clients with 3 transaction   25
No. of Clients with >3 transactions 259

我无法在SQL中思考如何解决这个问题,我可能会在Excel中解决这个问题,但我认为它是在服务器级别完成的。

5 个答案:

答案 0 :(得分:2)

我称之为"直方图的直方图"查询。只需使用group by两次:

select cnt, count(*), min(CLlient_Ref), max(Client_Ref)
from (select Client_Ref, count(*) as cnt
      from Transactions
      where Start_Date >= '2015-01-01'
      group by Client_Ref
     ) t
group by cnt
order by cnt;

我包含了min和max客户端引用,因为我经常想进一步调查某些值。

如果您希望限制为3,则可以使用case

select (case when cnt <= 3 then cast(cnt as varchar(255)) else '4+' end) as grp,
       count(*), min(CLlient_Ref), max(Client_Ref)
from (select Client_Ref, count(*) as cnt
      from Transactions
      where Start_Date >= '2015-01-01'
      group by Client_Ref
     ) t
group by (case when cnt <= 3 then cast(cnt as varchar(255)) else '4+' end) 
order by min(cnt);

答案 1 :(得分:0)

select cnt, count(*) from
(
select case count(*) when 1 then 'No. of Clients with 1 transaction'
                     when 2 then 'No. of Clients with 2 transactions'
                     when 3 then 'No. of Clients with 3 transactions'
                            else 'No. of Clients with >3 transactions'
       end as cnt
from Transactions
where Start_Date >= '2015-01-01'
group by Client_Ref
)
group by cnt

答案 2 :(得分:0)

您可以执行条件SUM()来提取每个分组的总数:

Select  'No. of Clients with 1 transaction' = Sum(Case When A.Total = 1 Then 1 Else 0 End),
        'No. of Clients with 2 transactions' = Sum(Case When A.Total = 2 Then 1 Else 0 End),
        'No. of Clients with 3 transactions' = Sum(Case When A.Total = 3 Then 1 Else 0 End),
        'No. of Clients with >3 transactions' = Sum(Case When A.Total > 3 Then 1 Else 0 End)
From    
(
    Select  Client_Ref, count(*) As Total
    From    Transactions
    Where   Start_Date >= '2015-01-01'
    Group by Client_Ref
) A

答案 3 :(得分:0)

您可以单独创建存储桶,然后使用union all

with COUNT1 as (
select Client_Ref, count(*) as count1
from Transactions
where Start_Date >= '2015-01-01'
group by Client_Ref
order by Client_Ref
    )
,COUNT2 as (
select cast(C.count1 as varchar(5)) as count1,count(Client_Ref) as count2
from COUNT1 C
where count1 <= 3
group by C.count1
    )
,COUNT3 as (
select '> 3' as count1,count(*) as count2
from COUNT1 C
where C.count1 > 3
    )

select * from COUNT2
union all
select * from COUNT3

如果您愿意,可以手动输入该文本('具有N个交易的客户数')。

答案 4 :(得分:0)

select Client_Ref
    ,count(*) as Count
    ,case when count(*) < 4 then count(*) else 4 end as Band
from Transactions
where Start_Date >= '2015-01-01'
group by Client_Ref
order by Client_Ref