coolair
V2EX  ›  问与答

请教一个 sql 怎么写

  •  
  •   coolair · Aug 7, 2020 · 3135 views
    This topic created in 2280 days ago, the information mentioned may be changed or developed.

    表结构如下:

    category state target_id
    a01
    a11
    b11
    b21
    c31
    d22

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

    Supplement 1  ·  Aug 7, 2020
    不好意思,前面表达有点错误,应该是同一分类所有 state>0 。
    是只有 b 、c 符合,结果是 2 。
    15 replies  •  2020-08-07 16:04:35 +08:00
    lxk11153
    lxk11153
    Aug 7, 2020
    1
    233 不支持表格,你可以学我这样子: /t/696035
    coolair
    coolair
    OP
    Aug 7, 2020
    2
    @lxk11153 #1 表格搞定,帮忙看看,多谢。
    DelayNoMay
    DelayNoMay
    Aug 7, 2020
    3
    用 group by category,再按条件 count 一下
    whisper3032
    whisper3032
    Aug 7, 2020
    4
    select count(distinct category) from table where target_id = 1 and state > 0
    coolair
    coolair
    OP
    Aug 7, 2020
    5
    搞表格搞了半天,现在主题不可编辑了,上面写错了,结果应该是只有 b 、c 符合,结果是 2.
    coolair
    coolair
    OP
    Aug 7, 2020
    6
    @lxk11153 #1 顺带告诉下你,表格可以直接在 markdown 语法下写<table><tr><td></td></tr></table>
    lxk11153
    lxk11153
    Aug 7, 2020
    7
    @coolair #2 怎么搞的? markdown+html(table)吗?
    lxk11153
    lxk11153
    Aug 7, 2020
    8
    @coolair #6 呵呵,我已经猜到。[doge]。同样表示感谢
    coolair
    coolair
    OP
    Aug 7, 2020
    9
    @whisper3032 #4
    @DelayNoMay #3 不好意思,前面表达有点错误,应该是同一分类所有 state>0 。
    DelayNoMay
    DelayNoMay
    Aug 7, 2020
    10
    select count(1) from table where state>0 and target_id = 1 group by category
    butterf1y
    butterf1y
    Aug 7, 2020
    11
    SELECT count(*) FROM(SELECT DISTINCT category from t_test WHERE target_id = 1 AND state > 0)as temp;
    flowfire
    flowfire
    Aug 7, 2020
    12
    不是 group by 吗。。。。子查询里 group by,再 count 计数
    但是感觉这么搞性能方面很堪忧
    shine20070522
    shine20070522
    Aug 7, 2020❤️4
    13
    group by category having min(state) > 0
    coolair
    coolair
    OP
    Aug 7, 2020
    14
    @shine20070522 #13 感谢老哥!
    zhuangjia
    zhuangjia
    Aug 7, 2020
    15
    考试场景:查找所有科目成绩都及格的同学人数
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   5217 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 82ms · UTC 06:15 · PVG 14:15 · LAX 22:15 · JFK 01:15
    ♥ Do have faith in what you're doing.