MySQL中的相同值未分组

MySQL中的相同值未分组,mysql,Mysql,我在两个单独的表中有两列(都是varchar(45)),它们都有值,比如0123456 我有一个联合查询,它基本上是将两个表中的行堆叠起来 select 'ISSUED' AS action, card_match_key AS card_match_key, count(0) AS CNT from dim_consumer_cards group by 1 , 2 union select 'REDEEMED' AS action, card_match_key AS card_

我在两个单独的表中有两列(都是varchar(45)),它们都有值,比如0123456

我有一个联合查询,它基本上是将两个表中的行堆叠起来

select 
'ISSUED' AS action,
card_match_key AS card_match_key,
count(0) AS CNT
from
dim_consumer_cards
group by 1 , 2 

union 

select 
'REDEEMED' AS action,
card_match_key AS card_match_key,
count(0) AS CNT
from
fct_card_redemptions
group by 1 , 2
然后是第二个查询,它在堆叠的数据上形成交叉表

Select
card_match_key as cardkey,
sum(case when action = 'ISSUED' then CNT else 0 end) as ISSUED,
sum(case when action = 'REDEEMED' then CNT else 0 end) as REDEEMED
from vw_rpt_matchkey1
group by 
card_match_key
我的问题是,我的值没有按相似的值分组(例如0123456)。
每个值应该只显示在一行上,但我得到的是两行。

请尝试将第一个查询更改为使用公共子表达式,如下所示:

with (
     select 
     'ISSUED' AS action,
     card_match_key AS card_match_key,
     from
     dim_consumer_cards
     UNION ALL
     select 
     'REDEEMED' AS action,
     card_match_key AS card_match_key,
     from
     fct_card_redemptions) AS combined
select action, card_match_key, count(1) as CNT
from combined
group by 1,2;

您需要先执行union操作,然后再执行group by。

如果未对它们进行分组,则它们的值不同。或者结果被读取错误“…然后是第二个查询,它在堆叠的数据上形成交叉表。”此操作应沿所述最终查询中指定的组平滑。