gpt4 book ai didi

mysql 查询 : how to get the number of yes/no votes per day

转载 作者:可可西里 更新时间:2023-11-01 06:53:26 24 4
gpt4 key购买 nike

我必须创建一个 mysql 查询来获取超过特定日期的每一天的投票分布,就像这样......

    date          yes_votes    no_votes
------------------------------------------
2010-01-07 21 22
2010-01-07 2 0

我的 table 是这样的..

    post_votes
--------------------------
id(longint)
date(timestamp)
flag(tinyint) // this stores the yes/no votes 1-yes, 2-no

我卡在这个....

SELECT COUNT(*) AS count, DATE(date) FROM post_votes WHERE date > '2010-07-01' GROUP BY DATE(date)

这给出了每天的投票总数,但不是我想要的分布。

最佳答案

SELECT COUNT(*) AS count
, DATE(date)
, SUM(flag = 1) AS yes_votes
, SUM(flag = 2) AS no_votes
FROM post_votes
WHERE date > '2010-07-01'
GROUP BY DATE(date)

这是一个适用于 MySQL 的技巧,因为 flag=1 将是 TrueFalse。但是 MySQL 中的 True = 1False = 0 因此您可以使用 SUM() 函数添加 1 和 0。

使用 IFCASE 的其他解决方案会更清晰,或者如果您想将数据库移动到另一个 RDBMS。

与问题无关的评论:

  • 使用datecount 等保留字来命名字段或表是个坏习惯。
  • 在实际存储时间戳时使用“日期”也不好。名称应反射(reflect)用途。
  • 对于表名,建议使用单数 (post_vote) 而不是复数 - 尽管许多人使用复数,但最终会让人感到困惑。复数适用于某些字段或计算字段,例如您的 yes_votesno_votes 我们有计数。

关于mysql 查询 : how to get the number of yes/no votes per day,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6211628/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com