MySql GROUP BY最大日期

时间:2018-03-21 02:39:59

标签: mysql sql join group-by max

我有一个名为votes的表格,其中有4列:idnamechoicedate

**** id {**** {1}} {**** {1}} {****** {1}} ***
**** name {***** {1}} {******* {1}} {****** {1}}
**** vote {***** {1}} {******* {1}} {****** {1}}
**** date {***** {1}} {******* {1}} {****** {1}}

我的最终目标是计算所有选票,但我只想计算每人1票,特别是每个人最近的投票。

在上面的示例中,结果应该是1票对A,1票对B。

以下是我目前的情况:

1

但是,这不起作用,因为子查询确实选择了最大日期,但它不包括与该最大日期相关联的正确sam

5 个答案:

答案 0 :(得分:2)

不要认为“分组”获得最近的投票。想想加入或其他一些选择。这是一种方式:

SELECT v.name,
       SUM(v.choice = 'A') as votesA,
       SUM(v.choice = 'B') as votesB
FROM votes v
WHERE v.date = (SELECT MAX(v2.date) FROM votes v2 WHERE v2.name = v.name)
GROUP BY v.name;

Here是一个SQL小提琴。

答案 1 :(得分:1)

您的答案很接近但需要JOIN自我

子查询按名称获取Max日期,然后JOIN自我。

select
    sum(case when T.vote = 'A' then 1 else 0 end) votesA,
    sum(case when T.vote = 'B' then 1 else 0 end) votesB
FROM (
    SELECT name,Max(date) as date
    FROM T
    GROUP BY name
) AS T1 INNER JOIN T ON T1.date = T.date

SQLFiddle

答案 2 :(得分:0)

试试这个

SELECT
    choice,
    COUNT(1)
FROM
    votes v
    INNER JOIN
    (
        SELECT
            id,
            max(date)
        FROM
            votes
        GROUP BY
            name
    ) tmp ON
    v.id = tmp.id
GROUP BY
    choice;

答案 3 :(得分:0)

select 
name,
sum( case when choice = 'A' then 1 else 0 end) voteA,
sum( case when choice = 'B' then 1 else 0 end) voteB
from
(
select id, name, choice
from votes
where date = (select max(date) from votes t2 
                where t2.name = votes.name ) 
) t
group by name

或者只为VoteA和VoteB的总计数输出一行:

select 
sum( case when choice = 'A' then 1 else 0 end) voteA,
sum( case when choice = 'B' then 1 else 0 end) voteB
from
(
select id, name, choice
from votes
where date = (select max(date) from votes t2 
                where t2.name = votes.name ) 
) t

答案 4 :(得分:0)

这样的事情(如果你真的需要只计算最后一次投票的人)

SELECT 
  sum(case when vote='A' then cnt else 0 end) voteA,
  sum(case when vote='B' then cnt else 0 end) voteB
FROM 
 (SELECT vote,count(distinct name) cnt
  FROM (
      SELECT name,vote,date,max(date) over (partition by name) maxd
      FROM votes
  ) 
  WHERE date=maxd
  GROUP BY vote
 )

PS。 MySQL v 8