如何创建列来衡量 SQL 中出现的次数?

How to create column that measures the number of occurrences in SQL?

我正在尝试计算特定列的唯一出现次数 - “car_id”例如,如果 Car_Shop_A 有 3 次出现 car_id 我想此计数将显示在 table 中,如下所示:"Shop1 - car_1 - 3"

SELECT
    shop_name,
    car_id,
    Count(car_id) as count
    
FROM
    car_database
WHERE
    date between '20210101' AND '2021131'
    AND shop_name IN ('Shop1',
                        'Shop2',
                        'Shop3',
                        'Shop4',
                        'Shop5',
                        'Shop6')
                        
                                
group by shop_name, car_id
order by count desc              

以上是我当前的查询,但是 returns 这个 table:

此查询 returns 所有商店的相同计数和 returns 行数而不是每个 car_id 出现的次数。我该如何解决这个问题?

如果我没听错的话,从分组中删除 car_id 列并将 DISTINCT 添加到计数函数应该 return 您需要的结果:

SELECT
    shop_name,
    Count(distinct car_id) as count
    
FROM
    car_database
WHERE
    date between '20210101' AND '2021131'
    AND shop_name IN ('Shop1',
                        'Shop2',
                        'Shop3',
                        'Shop4',
                        'Shop5',
                        'Shop6')
                        
                                
group by shop_name
order by count desc 
SELECT
    shop_name || ' - ' || car_id || ' - ' || count(1) as shop_car_listing
FROM
    car_database
WHERE
    date between '20210101' AND '2021131'
    AND shop_name IN ('Shop1',
                      'Shop2',
                      'Shop3',
                      'Shop4',
                      'Shop5',
                      'Shop6')                              
group by shop_name, car_id 
order by count(1) desc

fiddle