如何将非 NULL 的列计入相同的 table?
How to COUNT Column not NULL into same table?
如何计算非 Null 或零的 table 列并将结果插入 "Count" 列,如 Mysql 下面的 table?
column1 | column2 | column3 | column4 | Count
3 2 4 2 4
2 2 3 0 3
3 0 5 2 3
0 0 2 3 2
0 0 6 2 2
select
CT.Column1,
CT.Column2,
CT.Column3,
CT.Column4,
(
select count(*)
from (values (CT.column1), (CT.column2), (CT.column3), (CT.column4)) as v(col)
where v.col is not null
) as Count
from customtable as CT
一种方法是简单地使用 case
语句:
编辑:
要更新 table_name
中的 cnt
列,您可以使用:
update table_name
set cnt = (case when column1 is null or column1 = 0 then 0 else 1 end +
case when column2 is null or column2 = 0 then 0 else 1 end +
case when column3 is null or column3 = 0 then 0 else 1 end +
case when column4 is null or column4 = 0 then 0 else 1 end)
首先在第 3 行的 table 中,预期计数是 3,对吗?
一种肮脏的做法是将测试的整数值求和为 NULL 列(布尔值,因为 int 是 1 或 0 ):
SELECT
Column1, Column2, Column3, Column4,
(CAST(column1 is not null AS SIGNED INTEGER) +
CAST(column2 is not null AS SIGNED INTEGER) +
CAST(column3 is not null AS SIGNED INTEGER) +
CAST(column4 is not null AS SIGNED INTEGER)) as count
FROM (
SELECT 3 as column1,2 as column2,4 as column3,2 as column4
union select 2,2,3,NULL
union select 3,NULL,5,2
union select NULL,NULL,2,3
union select NULL,NULL,6,2
) as YourTable
试试这个查询。
更新集=sum(COUNT()-COUNT(column1) + COUNT()-COUNT(column2) + COUNT()-COUNT(column3 ) + COUNT()-COUNT(column4)) 其中 =;
如何计算非 Null 或零的 table 列并将结果插入 "Count" 列,如 Mysql 下面的 table?
column1 | column2 | column3 | column4 | Count
3 2 4 2 4
2 2 3 0 3
3 0 5 2 3
0 0 2 3 2
0 0 6 2 2
select
CT.Column1,
CT.Column2,
CT.Column3,
CT.Column4,
(
select count(*)
from (values (CT.column1), (CT.column2), (CT.column3), (CT.column4)) as v(col)
where v.col is not null
) as Count
from customtable as CT
一种方法是简单地使用 case
语句:
编辑:
要更新 table_name
中的 cnt
列,您可以使用:
update table_name
set cnt = (case when column1 is null or column1 = 0 then 0 else 1 end +
case when column2 is null or column2 = 0 then 0 else 1 end +
case when column3 is null or column3 = 0 then 0 else 1 end +
case when column4 is null or column4 = 0 then 0 else 1 end)
首先在第 3 行的 table 中,预期计数是 3,对吗? 一种肮脏的做法是将测试的整数值求和为 NULL 列(布尔值,因为 int 是 1 或 0 ):
SELECT
Column1, Column2, Column3, Column4,
(CAST(column1 is not null AS SIGNED INTEGER) +
CAST(column2 is not null AS SIGNED INTEGER) +
CAST(column3 is not null AS SIGNED INTEGER) +
CAST(column4 is not null AS SIGNED INTEGER)) as count
FROM (
SELECT 3 as column1,2 as column2,4 as column3,2 as column4
union select 2,2,3,NULL
union select 3,NULL,5,2
union select NULL,NULL,2,3
union select NULL,NULL,6,2
) as YourTable
试试这个查询。
更新集=sum(COUNT()-COUNT(column1) + COUNT()-COUNT(column2) + COUNT()-COUNT(column3 ) + COUNT()-COUNT(column4)) 其中 =;