我想从表的两个独立列中获取不同值的COUNT。
我的表是:
ID CR PB DB CB
-----------------------------
1 1000 1000
2 60000 1000
3 1000 (NULL)
4 1500000 13000
5 60000 12000
6 1000 (NULL)
预期产出:
CR PB cnt_crpb DB CB cnt_dbcb
1000 3 1000 2
60000 2 13000 1
1500000 1 12000 1
我试图在两个不同的表中分隔列CR PB
和DB CB
,并使用LEFT JOIN将它们连接起来,但由于MySQL不支持FULL OUTER JOIN,因此不会给出预期的输出。
我也尝试过使用UNION,但结果是行。
任何帮助将不胜感激......
谢谢你。
答案 0 :(得分:2)
我认为您需要使用union all
执行此操作:
select max(CRPB) as CRPB, max(CRPB_cnt) as CRPB_cnt, max(DBCB) as DBCB, max(DBCB_cnt) as DBCB_cnt
from ((select (@rn1 := @rn1 + 1) as rn, CRPB, count(CRPB) as CRPB_cnt, NULL as DBCB, NULL as DBCB_cnt
from table t cross join
(select @rn1 := 0) as vars
group by CRPB
) union all
(select (@rn2 := @rn2 + 1) as rn, NULL, NULL, DBCB, count(DBCB) as DBCB_cnt
from table t cross join
(select @rn2 := 0) as vars
group by DBCB
)
) x
group by rn;
无论哪个列表最长,都可以保证结果。
答案 1 :(得分:1)
请注意,您需要确定哪个列会产生更多结果,即CR PB
或DB CB
哪个产生最多结果将是您要做的第一个选择然后离开加入另一个。假设两个结果的结果数量不均匀
SELECT `CR PB`, cnt_crpb, `DB CB`, cnt_dbcb
FROM
( SELECT `CR PB`, COUNT(*) as cnt_crpb, @a := @a + 1 as num_rows_a
FROM test_table
CROSS JOIN (SELECT @a := 0 ) temp
WHERE `CR PB` is not null
GROUP BY `CR PB`
)t
LEFT JOIN
( SELECT `DB CB`, COUNT(*) as cnt_dbcb, @b := @b + 1 as num_rows_b
FROM test_table
CROSS JOIN (SELECT @b := 0)temp1
WHERE `DB CB` is not null
GROUP BY `DB CB`
)t1 ON t1.num_rows_b = t.num_rows_a;