如何从以下模式中提取SQL计数?

时间:2012-03-24 07:21:30

标签: sql sum

假设我有一个表MEETING如下

M_DATE
M_RACE_NO
M_VENUE
M_ATHLETE

主键是日期,比赛号,场地,运动员。每个日期/比赛号码/场地可以包含许多可能的运动员。假设对于特定的运动员我希望提取日期,比赛号,场地以及参加该特定日期/比赛的运动员总数/场地

e.g。假设运动员博尔特参加了两场比赛,总场数为7和9,我希望得到类似下面的内容

2011-10-03, 4, NY, 7
2010-24-02, 5, SY, 9

我知道它看起来像

SELECT M_DATE, M_RACE_NO, M_VENUE, SUM(...) FROM MEETING WHERE M_ATHLETE='Bolt'

我不确定在SUM

之后会发生什么

2 个答案:

答案 0 :(得分:3)

如果你的RDBMS支持这个:

SELECT M_DATE, M_RACE_NO, M_VENUE,
   COUNT(*) OVER (PARTITION BY M_DATE, M_RACE_NO, M_VENUE)
FROM MEETING
WHERE M_ATHLETE='Bolt'

如果不是:

select m1.m_date, m1.m_race_no, m1.m_venue, m2.count_races
from meeting m1
join (select m_date, m_race_no, m_venue, count(*) count_races
      from meeting group by m_date, m_race_no, m_venue) m2
  on m1.m_date = m2.m_date
  and m1.m_race_no = m2.m_race_no
  and m1.m_venue = m2.m_venue
where m1.m_athlete = 'Bolt'

答案 1 :(得分:3)

SELECT 
    m.m_date
  , m.m_race_no
  , m.m_venue
  , COUNT(*) AS cnt 
FROM 
        meeting AS m
    JOIN
        meeting AS m2
            ON  m2.m_date    = m.m_date
            AND m2.m_race_no = m.m_race_no
            AND m2.m_venue   = m.m_venue
WHERE 
    m.m_athlete = 'Bolt'
GROUP BY
    m.m_date
  , m.m_race_no
  , m.m_venue