SQL - 返回列的计数

时间:2015-02-10 18:15:50

标签: sql

SELECT * FROM table WHERE column2 = 'Y'

给了我

column1    column2
Item1        Y
Item1        Y
Item1        Y
Item1        Y
Item2        Y
Item2        Y
Item3        Y
Item4        Y

由此,我想返回column1项的计数:

Item1         4
Item2         2
Item3         1
Item4         1

什么代码可以给我这个结果?

修改 尝试SELECT *, COUNT(*)后,我收到错误消息:Column 'Column1' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

3 个答案:

答案 0 :(得分:2)

SELECT column1, count(*) y_count
FROM mytable
WHERE column2 = 'Y'
GROUP BY column1

答案 1 :(得分:0)

您可以使用GROUP BY子句和count

SELECT column1, COUNT(column1) count_y 
  FROM table_name 
  WHERE column2='Y' 
  GROUP BY column1

(免责声明:在PostgreSQL中测试)

答案 2 :(得分:0)

希望这会对你有所帮助

Select column1, count(*) 
from table group by column1