我有一张犯罪数据表。在简化版中,它看起来像这样:
表格标题:
crime_id, neighborhood, offense
表数据:
- 1, Old Town, robbery
- 2, Bad Town, theft
- 3, Bad Town, theft
- 4, Uptown, stolen auto
如果我SELECT * FROM mytable WHERE offense ='theft'
,则返回Bad Town的结果。但是,我正在排名,所以我真正感兴趣的是:
Old Town: 0
Bad Town: theft
Bad Town: theft
Uptown: 0
如何编写一个SELECT语句来返回存在盗窃的案例,还会返回没有指定攻击条目的邻居?
更新:这是我的实际选择。我在应用p.campbell和Gratzy非常友好地发布到SELECT的解决方案时遇到了问题。如何将CASE语句与COUNT(*)?
一起应用SELECT
cbn.neighborhoods AS neighborhoods,
COUNT(*) AS offenses,
TRUNCATE(((na.neighborhood_area_in_sq_meters /1000) * 0.000386102159),2) AS sq_miles,
( COUNT(*) / ((na.neighborhood_area_in_sq_meters /1000) * 0.000386102159) ) AS offenses_per_sq_mile
FROM
wp_crime_by_neighborhood cbn, wp_neighborhood_area na
WHERE
cbn.offense='theft'
AND
cbn.neighborhoods = na.neighborhoods
GROUP BY
cbn.neighborhoods
ORDER BY
offenses_per_sq_mile DESC
答案 0 :(得分:1)
试试这个:
SELECT cbn.neighborhoods AS neighborhoods,
CASE WHEN IFNULL(COUNT(*),0) > 0 THEN CONCAT(COUNT(*), ' ', offense)
ELSE '0'
END AS offenses
--- ... and the rest of your query
FROM wp_crime_by_neighborhood cbn
INNER JOIN wp_neighborhood_area na
ON cbn.neighborhoods = na.neighborhoods
WHERE cbn.offense='theft'
GROUP BY cbn.neighborhoods
--ORDER BY offenses_per_sq_mile DESC
答案 1 :(得分:1)
我认为使用案例陈述应该这样做。
http://dev.mysql.com/doc/refman/5.0/en/case-statement.html
类似
Select neighborhood,
case offense when 'theft' then offense else '0' end case
from table
答案 2 :(得分:1)
如果你想进行排名,那么获取Bad Town的盗窃数量不是更好吗?像这样:
select distinct mt.neighborhood, ifnull(total, 0)
from mytable mt
left join (
select neighborhood, count(*) as total
from mytable
where offense = 'theft'
group by neighborhood
) as t on t.neighborhood = mt.neighborhood
根据您提供的数据,此查询应返回:
Old Town: 0
Bad Town: 2
Uptown: 0
这对我来说排名更有用。您可以轻松地在那里下订单。