区别,统计,分组查询疯狂

时间:2011-10-14 03:04:43

标签: sql postgresql aggregate-functions

我正在尝试返回每学期的测试次数。我可以让计数返回,但我不能按术语分组。

我已经尝试了所有的东西,而且我得到的最接近的是按期限进行分组,但之后我的计数仅为1,这是不对的。

这是我现在拥有的。它只返回一个计数,如何按term_id对其进行分组?

SELECT COUNT(*) 
  FROM (SELECT DISTINCT ON(student_id, test_event_id, terf.term_id) student_id  
          FROM report.test_event_result_fact terf 
          JOIN report.growth_measurement_window gw on gw.term_id = terf.term_id 
          JOIN report.term t on t.term_id = terf.term_id 
          JOIN report.test tt on tt.test_id = terf.test_id 
         WHERE terf.partner_id = 98 
           AND growth_event_yn = 't' 
           AND gw.test_window_complete_yn = 't' 
           AND gw.growth_window_type = 'DISTRICT' 
           AND tt.test_type_description = 'SURVEY_WITH_GOALS') as TestEvents

1 个答案:

答案 0 :(得分:1)

在不了解您的设置的情况下,这是我最好的选择:

select term_id, count(*) AS count_per_term
  from (
    select Distinct on (student_id, test_event_id, terf.term_id)
            terf.term_id, student_id
      from report.test_event_result_fact terf
      join report.growth_measurement_window gw using (term_id)
      join report.term t using (term_id)
      join report.test tt using (term_id)
     where terf.partner_id = 98
        and growth_event_yn = 't'
        and gw.test_window_complete_yn = 't'
        and gw.growth_window_type = 'DISTRICT'
        and tt.test_type_description = 'SURVEY_WITH_GOALS') as TestEvents
  group by 1;