有没有办法从ORACLE中的日期中提取年份数据?计算用户投票

时间:2013-06-03 07:28:07

标签: sql oracle date

您好我正在创建一个数据库,用于跟踪用户为我们的某个产品投票的次数。

有没有办法可以更改下面的查询来计算每年的最大投票数?我正在使用Oracle SQL开发人员

创建表的结构为

Members(username, email, pwd) 
Votes (username*, prodCode*, score, voteDate)

请注意:

SELECT username, count(username)
FROM Votes NATURAL JOIN members
GROUP BY username, email
HAVING COUNT(*) >= All(SELECT count(username)
                   FROM Votes v1
                   GROUP BY username);

2 个答案:

答案 0 :(得分:4)

我不完全确定我理解你的问题,但是这样的事情可能会吗?

SELECT username, 
       extract(year from voteDate) as vote_year, 
       count(*) as votes_per_year,
       max(count(*)) over (partition by extract(year from voteDate)) as max_votes_per_year
FROM Votes vt
GROUP BY username, extract(year from voteDate);

这将为您提供每个用户和年份的计数以及每行中每年的最大数量。 (注意,成员表不是必需的,因为你显然不需要任何列)。

如果您需要在没有人投票的情况下显示零数(或者某个特定用户没有投票),那么您需要这样的内容:

with years as (
   select 2009 + level as year
   from dual
   connect by level <= 21
)  
SELECT username, 
       y.year, 
       count(vt.username) as votes_per_year,
       max(count(vt.username)) over (partition by y.year) as max_votes_per_year
FROM years y 
  LEFT JOIN Votes vt on y.year = extract(year from vt.voteDate)
GROUP BY username, y.year
order by y.year, username;

这将使用公用表表达式(with ...)生成2010年至2030年间“即时”的年份列表。您可以调整CTE以延长或缩短年数。

答案 1 :(得分:0)

为此你最好有一张带有年份的表格(或者至少有一张数字表可以帮助你设定一组年份。)

SELECT
    username
    , MAX(cnt) AS mcnt
FROM (
    SELECT
        username
        , count(username) AS cnt
    FROM members 
    CROSS JOIN Years
    INNER JOIN Votes ON (
        members.username = Votes.username -- using an INT here would be more efficient
        AND
        Votes.voteDate >= Years.firstJanuary
        AND
        Votes.voteDate < Years.firstJanuary+ 1 Year -- Pseudo code, you didn't mention any DBMS
    )
    GROUP BY username, prodCode, Years.firstJanuary
) AS X