简体   繁体   中英

SQL counting different column values

I have a table called spider_status which has a status_code and a locationid. I am retrieving all cities from region_select_city which I joined in the code below. Now I am trying to count all the unique values in status_code in the table spider_status grouping by cities.

SELECT region_select_city.name as stad , COUNT(spider_status.id) as spider_aantal,
CASE WHEN spider_status.status_code = 1 THEN COUNT(spider_status.status_code) ELSE 0  END as LIVE
FROM
spider_status
 JOIN 
location 
ON spider_status.location_id = location.id
 JOIN
location_select_addressid 
ON location.id = location_select_addressid.locationid
JOIN
location_address
ON location_select_addressid.addressid = location_address.id 
JOIN
region_select_city 
ON location_address.city_id = region_select_city.id
JOIN
spider_status_code
ON spider_status.status_code = spider_status_code.id 
WHERE spider_status.current = 1
GROUP BY region_select_city.name 

Hope the following code help you to solve the issue

SELECT count(DISTINCT s.status_code) 
FROM spider_status AS s 
JOIN location AS l
ON l.locationid = s.locationid
JOIN location_address AS loc_add
ON loca_add.locationid = loc_add.locationid
GROUP BY loc_add.city_id

在最后第二行的末尾,AND是否应该存在?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM