计数出现的不同值而没有分组?

问题描述 投票:0回答:1

我需要逐行提取而不对所有clientID进行分组,请参见下文。

我正在写一个快速摘录,以查找我们的客户预订产品的次数,以便我们了解他们第二,第三或第四次预订的情况。

select c.clientid, c.bookref, left(c.tourno, 6) as tourref, c.book_date
from cust c

where c.book_date between '2018-01-01' and ' 2020-01-01'

order by clientid asc, book_date asc

这是非常基本的SQL,每次预订只需要一行结果。我需要做的是计算ClientID出现的次数,并通过“ clientid asc,book_date asc”对表进行排序,我应该能够得出一长串的预订清单,以及与每行对应的预订号码。

[不幸的是,我看到的所有帮助示例基本上都将ID列归为一类,因此我可以看到ID“ 255253”的计数为7(因此有7个预订),但不知道这些预订是什么。

谢谢!我正在使用Advantage SQL。

sql advantage-database-server
1个回答
0
投票

您可以使用窗口功能:

select c.clientid, c.bookref, left(c.tourno, 6) as tourref, c.book_date,
       count(*) over (partition by c.clientid) as client_cnt
from cust c
where c.book_date between '2018-01-01' and '2020-01-01'
order by clientid asc, book_date asc;

AdvantageSQL可能不支持这些。您可能可以将所需的内容连接在一起:

select c.clientid, count(*) as client_cnt,
       group_concat(c.bookref order by book_date)
from cust c
where c.book_date between '2018-01-01' and '2020-01-01'
group by clientid asc;
© www.soinside.com 2019 - 2024. All rights reserved.