Sql 如何计算列数

Sql 如何计算列数,sql,sql-server,count,Sql,Sql Server,Count,表1'样本数据: ID value1 Value2 value3 001 10 20 30 002 20 10 null 003 10 null null 004 10 null 30 .... create table ColumnCount ( ID char(3) not null, Value1 int, Value2 int, Value3 int ) insert into ColumnCount(ID,Value1,Value2,Value3)

表1'样本数据:

ID value1 Value2 value3

001 10 20 30
002 20 10 null
003 10 null null
004 10 null 30
....
create table ColumnCount (
    ID char(3) not null,
    Value1 int,
    Value2 int,
    Value3 int
)

insert into ColumnCount(ID,Value1,Value2,Value3)
select '001',10,20,30
union all select '002',20,10,null
union all select '003',10,null,null
union all select '004',10,null,30
union all select '005',null,null,null
从表1中,我想做一个coulmn计数

行查询计数

从表1中选择count(*)
,它将只给出行计数

但我需要列计数,其中的列值不应为null

预期产量

 ID   | totcolumn
-----------------
 001     3
 002     2
 003     1
 004     2
....

如何进行查询,需要查询帮助

使用
SUM
如下:

SELECT id,
       SUM(CASE WHEN value1 IS NULL then 0 ELSE 1 END) +
       SUM(CASE WHEN value2 IS NULL then 0 ELSE 1 END) +
       SUM(CASE WHEN value3 IS NULL then 0 ELSE 1 END) AS 'COUNT'
FROM table1
group by id

如果我理解正确的话,你需要的是这样的东西

从表1中选择ISNULL(Value1,0)+ISNULL(Value2,0)+ISNULL(Value3,0)作为_和


如果值为NULL,ISNULL将用0替换该值。如果您使用的是MS SQL Server 2005或更高版本,这是使用UNPIVOT的好机会。首先设置一些示例数据:

ID value1 Value2 value3

001 10 20 30
002 20 10 null
003 10 null null
004 10 null 30
....
create table ColumnCount (
    ID char(3) not null,
    Value1 int,
    Value2 int,
    Value3 int
)

insert into ColumnCount(ID,Value1,Value2,Value3)
select '001',10,20,30
union all select '002',20,10,null
union all select '003',10,null,null
union all select '004',10,null,30
union all select '005',null,null,null
我在上面提供的示例数据中添加了005,以说明如何处理所有ValueX列都为null的情况

UNPIVOT为您“规范化”数据,以便您可以对行使用计数:

select *
from ColumnCount
unpivot (Value for ValueN in (Value1, Value2, Value3)) as upvt

ID  Value   ValueN
001 10  Value1
001 20  Value2
001 30  Value3
002 20  Value1
002 10  Value2
003 10  Value1
004 10  Value1
004 30  Value3
请注意,它已经消除了空值,因此您不必这样做。不幸的是,这意味着,如果您进行简单的计数,则所有ValueX列(例如,ID='005')中均为NULL的行将不会显示。相反,在子查询或CTE中收集所有ID,如下面的AllID:

with ColumnsOnRows as (
    select *
    from ColumnCount
    unpivot (Value for ValueN in (Value1, Value2, Value3)) as upvt
),
AllIds as (
    select distinct ID
    from ColumnCount
)
select AllIds.ID, count(distinct Value) as totcolumn
from AllIds
left outer join ColumnsOnRows
on ColumnsOnRows.ID = AllIds.ID
group by AllIds.ID
结果:

ID  totcolumn
001 3
002 2
003 1
004 2
005 0

这没有帮助,这将对值进行求和
value1
+
value2
+
value3
而不计算它们,因此它将分别给他
60、30、10、40
,OP不希望这样。您需要使用pivot进行此操作。如果您的表中有编号的列,这通常是一个设计问题,您应该将这些列拆分为新表中的行。然后您可以
COUNT()
这些行。