2

我想知道是否有办法简化下面的 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 中完成吗?

4

3 回答 3

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
于 2012-08-19T20:54:11.797 回答
2
select count(name) name_count,
       count(coalesce(nullif(l1,''), nullif(l2,''))) l1_or_l2_count,
       count(sch) sch_count
  from your_table;
于 2012-08-19T20:56:34.033 回答
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
于 2012-08-19T20:54:01.057 回答