2016-08-18 40 views
4

下面是插入数据的表。SQL查询使列表更多

CREATE TABLE police(event_id VARCHAR(100), search_type VARCHAR(1000), 
        reported_by VARCHAR(100)); 
INSERT INTO police VALUES ('gng67g6yf', 'person','ceridigion'); 
INSERT INTO police VALUES ('bfewbqfjhfb', 'person', 'ceridigion'); 
INSERT INTO police VALUES ('ytftdfctg', 'n/a','ceridigion' ); 
INSERT INTO police VALUES ('yufvugyu', 'person','pembrokeshire', ); 

我想知道的是一个查询,它将列出reported_by并进行在这些区域中进行的搜索。事情是这样的下面:

reported_by  Stopped and searched 
ceridigion    2 
pembrokeshire   1 

回答

1
SELECT reported_by, 
     SUM(CASE WHEN search_type = 'person' THEN 1 ELSE 0 END) AS `Stopped and searched` 
FROM police 
GROUP BY reported_by 

演示在这里:

SQLFiddle

1

如果我理解正确的话,你只需要计算行(即有search_type数每reported_by那不是n/a

SELECT reported_by, COUNT(*) AS "Stopped and searched" 
FROM  police 
WHERE search_type != 'n/a' 
GROUP BY reported_by