V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
• 请不要在回答技术问题时复制粘贴 AI 生成的内容
yuanfnadi
V2EX  ›  程序员

写数据库语句遇到问题

  •  
  •   yuanfnadi · Aug 8, 2017 via iPhone · 2188 views
    This topic created in 3184 days ago, the information mentioned may be changed or developed.
    表有两列
    a b
    1 2
    1 3
    2 3
    2 1
    2 2


    现在要求出所有的数字一共出出现了几列
    结果应该是
    1 3
    2 4
    3 3

    用数据库写我想到的方法是分别求出两列个数,相加以后减去相同的个数
    8 replies    2017-08-13 13:05:27 +08:00
    yejinmo
        1
    yejinmo  
       Aug 8, 2017
    结果应该是
    1 3
    2 5
    3 3
    xxoxx
        2
    xxoxx  
       Aug 8, 2017
    目测了一下,结果应该是
    1 3
    2 5
    3 2
    yejinmo
        3
    yejinmo  
       Aug 8, 2017
    select a, count(a) from
    (
    (select a from test union all select b from test) as temp
    )
    group by a;
    yejinmo
        4
    yejinmo  
       Aug 8, 2017
    @yejinmo
    1 3
    2 5
    3 2
    yuanfnadi
        5
    yuanfnadi  
    OP
       Aug 8, 2017 via iPhone
    重复的不算
    应该是
    13
    24
    32

    33 是手抖了
    akira
        6
    akira  
       Aug 8, 2017
    SELECT a, SUM(`t`) `count`
    FROM
    (
    SELECT a, COUNT(a) `t`
    FROM test
    GROUP BY a UNION
    SELECT b, COUNT(b)
    FROM test
    WHERE a<>b
    GROUP BY b
    )tt
    GROUP BY a
    zeraba
        7
    zeraba  
       Aug 8, 2017 via Android
    就按照你的思路 把 a b 先并到一起 参考 3 楼 一样的随便取一个 最后 group by
    伪代码
    select case when a = b then a else a end hebing from test
    union
    select case when a <> b then b end hebing
    SuperMild
        8
    SuperMild  
       Aug 13, 2017
    select a, sum(num) as 'count' from
    (select a, count(a) as num from AandB where a <> b group by a
    union all
    select b, count(b) from AandB where a <> b group by b
    union all
    select b, count(b) from AandB where a = b group by b)
    group by a;
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5029 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 48ms · UTC 01:09 · PVG 09:09 · LAX 18:09 · JFK 21:09
    ♥ Do have faith in what you're doing.