我想知道是否有办法简化以下SQL语句。这是我的桌子。
| SID | name | l1 | l2 | sch |
| 1 | john | | | sch |
| 2 | mary | l1 | | |
| 3 | zack | l1 | l2 | |
| 4 | paul | l1 | l2 | sch |
填充l1或l2,或者两者都可以填充
并非每个'sch'都有值
我所做的是计算每日汇总表,但我是通过PHP完成的,我想知道是否可以使用SQL来完成。所以,例如,
- Total count (This is just count(name))
- Count(sch)
- If !empty (l1) OR !empty (l2) THEN l + 1
所以现在,基于以上
Total count = 4
count(sch) = 2
count(l1 || l2) = 3
可以在SQL中完成吗?
答案 0 :(得分:3)
您没有说l1,l2和sch列是否包含NULL。
如果这些列不能包含NULL,则mysql查询将如下:
SELECT COUNT(*) AS `count`, SUM(sch<>'') AS count_sch,
SUM(l1<>'' OR l2<>'') AS count_l
FROM your_table
如果这些列可以包含NULL,则mysql查询将类似于:
SELECT COUNT(*) AS `count`, SUM(sch IS NOT NULL) AS count_sch,
SUM(l1 IS NOT NULL OR l2 IS NOT NULL) AS count_l
FROM your_table
答案 1 :(得分:2)
select count(name) name_count,
count(coalesce(nullif(l1,''), nullif(l2,''))) l1_or_l2_count,
count(sch) sch_count
from your_table;
答案 2 :(得分:0)
是:
select count(*) as count, count(sch) as school,
sum(case when l1 is not null or l2 is not null then 1 else 0 end)
from table