如何构造此查询

时间:2011-07-23 12:23:26

标签: mysql database

我有以下两个问题:

  

SELECT CARD_ID,COUNT(CARD_ID)AS CNT1来自G_CARD_SCHEDULE GROUP BY   card_id的

谁的输出是

CARD_ID     CNT1
119         1
120         2
  

从G_SENT_TABLE GROUP BY中选择CARD_ID,COUNT(CARD_ID)作为CNT2   card_id的

谁的输出是

CARD_ID     CNT2
115         2
120         1

现在我的查询应该使用这两个

输出
CARD_ID     CNT2
120         3
115         2
119         1

所以基本上我必须通过ID排序得到它们的总和。我该怎么做?

3 个答案:

答案 0 :(得分:2)

select card_id,count(card_id) as cnt2 from (
SELECT CARD_ID FROM G_CARD_SCHEDULE 
union all
SELECT CARD_ID FROM G_SENT_TABLE) as t
group by card_id
order by cnt2 desc

答案 1 :(得分:2)

  SELECT CARD_ID,
         COUNT(*) cnt
    FROM (SELECT card_id 
            FROM G_CARD_SCHEDULE
          UNION ALL
          SELECT card_id
            FROM G_SENT_TABLE) x
GROUP BY card_id
ORDER BY cnt DESC

答案 2 :(得分:0)

怎么样:

SELECT CARD_ID, COUNT(CARD_ID) FROM 
      (SELECT CARD_ID FROM G_CARD_SECHEDULE 
   UNION ALL 
       SELECT CARD_ID FROM G_SENT_TABLE)
   AS G_CARD_UNION GROUP BY CARD_ID;

......那会得到你想要的吗?