如何在一个表中选择列的记录数

时间:2014-10-15 20:09:06

标签: sql select subquery union

我有这样的表结构:

  id - person_name - date

- 1 - Tester - 15-10-2014 
- 2 - Tester - 15-10-2014
- 3 - Tester - 15-09-2014
- 4 - Coder  - 15-10-2014

我需要选择人和每个人最小。 3个月的记录数。

赞:name =>测试仪; month1 => 2; month2 => 1 ;; name =>编码器; month1 => 1; month2 => 0

SELECT person_name, 
       COUNT(person_name) AS month1
FROM table
WHERE MONTH(date) = "10" GROUP BY person_name

这给了我很好的结果,比如name =>测试; month1 => 2 ...但我还需要其他选择选择其他月份,我尝试工会等等,没有任何成功。感谢

2 个答案:

答案 0 :(得分:1)

如果您需要获得所有月份和所有人,则需要更复杂的查询。从您需要生成的所有行开始,然后使用left joingroup by

select n.person_name, ym.y, ym.m, count(t.person_name)
from (select distinct person_name from table) n cross join
     (select distinct year(date) as y, month(date) as m from table) ym left join
     table t
     on t.person_name = n.person_name and year(t.date) = ym.y and month(t.date) = ym.m
group by n.person_name, ym.y, ym.m;

答案 1 :(得分:0)

如果我理解这个问题,你只需要在月份上分组,并举例说明文件管理器。沿着:

SELECT person_id
      ,MONTH(date)
      ,COUNT(person_id)
  FROM table
 WHERE MONTH(date) IN (8,9,10)
 GROUP BY person_id
         ,MONTH(date)

[EDIT] with pivot。

SELECT * 
  FROM (SELECT person_id
             , MONTH(dttm) MonthId 
          FROM tbl) SourceTable     
 PIVOT (COUNT(MonthId) 
          FOR MonthId IN ([8],[9],[10])
       ) PivotTable