0

现在我有以下查询:

SELECT     
  rm.reward_name,
  rm.rewardid,
  rc.reward_code,
  rc.status,
  rc.rewardid,
  rc.add_date,
  rc.status 
from rewards_codes as rc 
INNER JOIN reward_mast as rm on rc.rewardid on rm.rewardid 
where DATE(rc.add_date) between '2012-03-16' AND '2013-03-16';

我想从所有代码中获取代码总数,可用代码,使用代码

我已在rewards_codes 字段中使用状态字段来区分代码状态

0 - 可用

1-使用的代码

所以我的最终输出应该如下所示:

-----------------------------------------------------------
Reward Name     Total Codes      Available code   Used code        

my_reward       100                  40               60
extra_reward    100                  90               10
-----------------------------------------------------------

[更新]

这是两个表中的一些示例数据...

reward_mast

rewardid        rewrd_name
1               my_reward
2               extra_reward
3               test_reward

奖励代码

codeId  rewardid    reward_code     add_date    status
1       1           aka454          2012-11-21  0
2       2           ala499          2012-04-21  0
3       1           pao789          2012-08-21  0
4       3           zlk753          2012-01-21  0
5       2           qra954          2012-05-21  0
4

1 回答 1

1

尝试这个:

SELECT 
  rm.rewardid,
  rm.reward_name,
  IFNULL(COUNT(rc.reward_code), 0) AS 'Total Codes',
  IFNULL(SUM(rc.status = 0), 0)    AS 'Available code',
  IFNULL(SUM(rc.status = 1), 0)    AS 'Used Codes'
FROM reward_mast as rm
LEFT JOIN rewards_codes as rc on rc.rewardid = rm.rewardid 
WHERE DATE(rc.add_date) between '2012-03-16' AND '2013-03-16'
GROUP BY rm.reward_name,
         rm.rewardid;

这将分别为您提供每种状态代码类别的计数TotalcodesAvailable CodesUsed Codes

SQL 小提琴演示

这会给你:

| REWARDID |  REWARD_NAME | TOTAL CODES | AVAILABLE CODE | USED CODES |
-----------------------------------------------------------------------
|        1 |    my_reward |           2 |              2 |          0 |
|        2 | extra_reward |           2 |              2 |          0 |
于 2013-03-16T07:15:35.630 回答