我正在尝试获得如下所示的结果,列名无关紧要,以后我可以对其进行编辑。
Date - Visit Amount- Customer Count by Visit Amount
2020 1 10
2020 2 50
2020 3 123
2020 6 24
我有date和customer_id列。简而言之,我试图确定在2020年有1次,2次等访问过我的商店的顾客有多少。我找不到,因为访问量无法分组。
答案 0 :(得分:0)
我试图在2020年发现有1次,2次等的顾客来过我的商店。
您可以使用两种聚合级别:
select num_visits, count(*) as num_customers
from (select customer_id, count(*) as num_visits
from visits v
where visit_dt >= '2020-01-01' and visit_dt < '2021-01-01'
group by customer_id
) v
group by num_visits
order by num_visits;
这构成了表名和列名,因为您的问题未提供它们。但是应该很容易看到它在做什么。
编辑:
如果要分别每年:
select year, num_visits, count(*) as num_customers
from (select year(visit_dt) as year, customer_id, count(*) as num_visits
from visits v
group by year(visit_dt), customer_id
) v
group by year, num_visits
order by year, num_visits desc;
答案 1 :(得分:0)
您可以使用CTE。
WITH TBL AS (
--your first grouping query here
),
AS TBL2 (
SELECT
COUNT(Visit_Amount) Visit_Amount,
COUNT(Customer_Count_by_Visit_Amount) Customer_Count_by_Visit_Amount
FROM TBL
GROUP BY Visit_Amount,Customer_Count_by_Visit_Amount
)
SELECT * FROM TBL2