dongnanman9093 2011-07-13 22:43
浏览 249
已采纳

MYSQL:除了0和null之外的所有值的GROUP BY?

I have a simple SQL Query:

  SELECT tid, 
         COUNT(*) AS bpn
    FROM mark_list 
   WHERE userid = $userid 
GROUP BY tid

Now the column tid is basically a category list associated with each entry. The categories are unique numeric values.

What I am trying to do is get an overall count of how many records there as per userid, but I only want to count an entire category one time (meaning if category 3 has 10000 records, it should only receive a count of 1).

The caveat is that sometimes the category is listed as null or sometimes a 0. If the item has either a 0 or a null, it has no category and I want them counted as their own separate entities and not lumped into a single large category.

  • 写回答

2条回答 默认 最新

  • duannan4486 2011-07-13 22:48
    关注

    Wheeee!

    SELECT SUM(`tid` IS NULL) AS `total_null`,
           SUM(`tid` = 0) AS `total_zero`, 
           COUNT(DISTINCT `tid`) AS `other`
      FROM `mark_list`
     WHERE `user_id` = $userid
    

    Edit: note that if total_zero is greater than 0, you will have to subtract one from the "other" result (because tid=0 will get counted in that column)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器