V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
coolair
V2EX  ›  问与答

请教一个 sql 怎么写

  •  
  •   coolair · 2020-08-07 14:48:36 +08:00 · 1621 次点击
    这是一个创建于 1351 天前的主题,其中的信息可能已经有所发展或是发生改变。

    表结构如下:

    category state target_id
    a01
    a11
    b11
    b21
    c31
    d22

    想要的结果是: target_id 为 1 且 state>0 的 category 类别的的个数,比如,以上只有 a 、b 、c 符合,所以,结果是 3 。

    第 1 条附言  ·  2020-08-07 15:25:02 +08:00
    不好意思,前面表达有点错误,应该是同一分类所有 state>0 。
    是只有 b 、c 符合,结果是 2 。
    15 条回复    2020-08-07 16:04:35 +08:00
    lxk11153
        1
    lxk11153  
       2020-08-07 14:50:19 +08:00
    233 不支持表格,你可以学我这样子: /t/696035
    coolair
        2
    coolair  
    OP
       2020-08-07 14:54:11 +08:00
    @lxk11153 #1 表格搞定,帮忙看看,多谢。
    DelayNoMay
        3
    DelayNoMay  
       2020-08-07 14:54:18 +08:00
    用 group by category,再按条件 count 一下
    whisper3032
        4
    whisper3032  
       2020-08-07 14:54:37 +08:00
    select count(distinct category) from table where target_id = 1 and state > 0
    coolair
        5
    coolair  
    OP
       2020-08-07 14:55:02 +08:00
    搞表格搞了半天,现在主题不可编辑了,上面写错了,结果应该是只有 b 、c 符合,结果是 2.
    coolair
        6
    coolair  
    OP
       2020-08-07 14:56:20 +08:00
    @lxk11153 #1 顺带告诉下你,表格可以直接在 markdown 语法下写<table><tr><td></td></tr></table>
    lxk11153
        7
    lxk11153  
       2020-08-07 14:56:52 +08:00
    @coolair #2 怎么搞的? markdown+html(table)吗?
    lxk11153
        8
    lxk11153  
       2020-08-07 14:57:37 +08:00
    @coolair #6 呵呵,我已经猜到。[doge]。同样表示感谢
    coolair
        9
    coolair  
    OP
       2020-08-07 14:57:42 +08:00
    @whisper3032 #4
    @DelayNoMay #3 不好意思,前面表达有点错误,应该是同一分类所有 state>0 。
    DelayNoMay
        10
    DelayNoMay  
       2020-08-07 14:58:36 +08:00
    select count(1) from table where state>0 and target_id = 1 group by category
    butterf1y
        11
    butterf1y  
       2020-08-07 14:59:00 +08:00
    SELECT count(*) FROM(SELECT DISTINCT category from t_test WHERE target_id = 1 AND state > 0)as temp;
    flowfire
        12
    flowfire  
       2020-08-07 15:08:50 +08:00
    不是 group by 吗。。。。子查询里 group by,再 count 计数
    但是感觉这么搞性能方面很堪忧
    shine20070522
        13
    shine20070522  
       2020-08-07 15:21:26 +08:00   ❤️ 4
    group by category having min(state) > 0
    coolair
        14
    coolair  
    OP
       2020-08-07 15:28:39 +08:00
    @shine20070522 #13 感谢老哥!
    zhuangjia
        15
    zhuangjia  
       2020-08-07 16:04:35 +08:00
    考试场景:查找所有科目成绩都及格的同学人数
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2760 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 12:46 · PVG 20:46 · LAX 05:46 · JFK 08:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.