mysql同一字段多条件查询
mysql同一字段多条件求和查询(if用法), 抽奖记录表
例子:抽奖记录表,需要查询每天抽奖人数(去重)、每一种抽奖类型的总数、领取总数
表结构:
CREATE TABLE `lottery` (
`id` int(10) NOT NULL COMMENT '主键id',
`uid` int(10) NOT NULL COMMENT '用户id',
`dateline` int(11) NOT NULL COMMENT '时间',
`type` tinyint(1) NOT NULL COMMENT '奖品类型:1:现金,2.优惠卷,3.积分',
`is_get` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否领取'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='抽奖记录表';
sql语句:
SELECT FROM_UNIXTIME(`dateline`,'%Y-%m-%d') AS days,
COUNT(DISTINCT(`uid`)) AS uids,
SUM(`is_get`) AS `get`,
COUNT(`id`) AS cj,
COUNT(IF(type = 1,TRUE,NULL)) AS xj,
COUNT(IF(type = 2,TRUE,NULL)) AS yhj,
COUNT(IF(type = 3,TRUE,NULL)) AS jf
FROM `lottery` GROUP BY days;
查询结果:
日期 | 抽奖人数 | 领取人数 | 现金(总数) | 优惠劵(总数) | 积分(总数) |
2016-11-11 | 1024 | 891 | 123 | 666 | 235 |
2016-11-15 | 789 | 555 | 66 | 500 |
223 |