GROUP BY的SQL语句

时间:2013-08-28 09:14:31

标签: mysql sql select

我真的被一个sql select语句所困扰。

这是我从下面的sql语句得到的输出/结果:

enter image description here

我需要什么:我需要通过msisdn在一行中将rowsWouchersNumber和usedVouchersNumber一起分配。因此,例如,如果您可以看到“msisdn”723709656,则现在有两行..一个具有assignedVouchersNumber = 1,第二个具有assignedVouchersNumber = 1。

但是我需要将它与assignedVouchersNumber = 2在一行中。你现在问题出在哪里了吗?

SELECT eu.msisdn,
   eu.id as userId,

   sum(case ev.voucherstate when '1' then 1 else 0 end) as assignedVouchersNumber,
   sum(case ev.voucherstate when '2' then 1 else 0 end) as usedVouchersNumber,

   ev.extra_offer_id,
   ev.create_time,
   ev.use_time,
   ev.id as voucherId,
   ev.voucherstate
FROM   extra_users eu
   JOIN (SELECT sn.msisdn AS telcislo,
                stn.numberid
         FROM   stats_number sn
                JOIN stats_target_number AS stn
                  ON ( sn.numberid = stn.numberid )
         WHERE  stn.targetid = 1) xy
     ON eu.msisdn = xy.telcislo
   JOIN extra_vouchers AS ev
     ON ( eu.id = ev.extra_user_id )
WHERE  ev.create_time BETWEEN '2012-07-23 00:00:00' AND '2013-08-23 23:59:59'
   AND ev.use_time <= '2013-08-23 23:59:59'
   AND ev.use_time >= '2012-07-23 00:00:00'
   AND ev.voucherstate IN ( 1, 2 )
   AND Ifnull(ev.extra_offer_id IN( 2335, 3195, 30538 ), 1)
   GROUP BY eu.msisdn, ev.extra_offer_id, ev.voucherState
ORDER  BY eu.msisdn ASC  

2 个答案:

答案 0 :(得分:1)

对于相同的msisdn和VouchersNumber,您有两个不同的extra_offer_id。这就是为什么你得到两行。

答案 1 :(得分:1)

我明白了......

中不应该通过ev.voucherState进行灌输
GROUP BY eu.msisdn, ev.extra_offer_id, ev.voucherState

之后我删除了它正在运行的ev.voucherState。