SQL计算不同的列值

时间:2016-01-07 12:44:31

标签: mysql case

我有一个名为spider_status的表,它有一个status_code和一个locationid。我正在从region_select_city中检索所有城市,我在下面的代码中加入了这些城市。现在,我试图计算每个城市的spider_status表中status_code中的所有唯一值。

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 

2 个答案:

答案 0 :(得分:1)

希望以下代码可以帮助您解决问题

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

答案 1 :(得分:0)

在最后一行的末尾,AND应该在那里吗?