MySQL COUNT()+半秒COUNT

时间:2013-12-02 16:43:02

标签: php mysql count

我有下表,我试图计算'名称'和' name2'列,但只添加一半的计数值,如果' name2' != NULL。还可以像以前一样创建另一个列,它也会检查“活动”列。值。

例如,我的表

ID  |  Name1 | Name2 |  Active 
------------------------------
1   |  John  |       | True
2   |  Mike  |  John | True
3   |  Tim   |       | False
4   |  Tim   |  Burt | False

结果,我试图创建

Names | Split_Count | Active_Count
Burt  |     0.5     |    0
John  |     1.5     |    1.5
Mike  |     0.5     |    0.5
Tim   |     1.5     |    0

到目前为止,我只能计算整数,所以在PHP中这样做会更好吗?

非常感谢所有帮助。

编辑:为了澄清,查询将名称为++ 1,但如果行中有2个名称,则每个名称都为+0.5。

其中,Active_Count将与上面的相同,其中ACTIVE = TRUE。

1 个答案:

答案 0 :(得分:0)

我想我明白你的意思。放手一搏:

create table person
(
id int unsigned not null primary key auto_increment,
Name1 varchar(50) default null,
Name2 varchar(50) default null,
Active varchar(50) not null default 'True'
);

insert into person (Name1,Name2,Active) values ('John',null,'True');
insert into person (Name1,Name2,Active) values ('Mike','John','True');
insert into person (Name1,Name2,Active) values ('Tim',null,'False');
insert into person (Name1,Name2,Active) values ('Tim','Burt','False');

select person as Names,
sum(splitScore) as Split_Count,
sum(activeScore) as Active_Count
from
(
select Name1 as person, 
case when Name2 is null then 1 else 0.5 end as splitScore,
case when Active='True' and Name2 is null then 1 when Active='True' and Name2 is not null then 0.5 else 0 end as activeScore 
from person where Name1 is not null
union all
select Name2 as person, 
case when Name1 is null then 1 else 0.5 end as splitScore,
case when Active='True' and Name1 is null then 1 when Active='True' and Name1 is not null then 0.5 else 0 end as activeScore 
from person where Name2 is not null
) t
group by person
;