[英]How to create column that measures the number of occurrences in SQL?
I am trying to count the number of unique occurrences of a certain column - "car_id" For example, if Car_Shop_A has 3 occurrences of a certain car_id I would like this count to be displayed in the table like so: "Shop1 - car_1 - 3"我正在尝试计算特定列的唯一出现次数 - “car_id” 例如,如果 Car_Shop_A 有 3 次出现特定的 car_id 我希望这个计数像这样显示在表中: “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
The above is my current query, however it returns this table:以上是我当前的查询,但它返回此表:
This query returns the same count for all shops and returns the number of rows rather than the number of each car_id occurrence.此查询为所有商店返回相同的计数,并返回行数而不是每个 car_id 出现的次数。 How can I fix this?
我怎样才能解决这个问题?
If I've understood you correctly, removing the car_id column from the grouping and adding DISTINCT to the count function should return the result you need:如果我理解正确,从分组中删除 car_id 列并将 DISTINCT 添加到计数 function 应该返回您需要的结果:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.