如何在不将NULL数据更改为0的情况下在临时表中包括NULL值的计数?

时间:2019-04-02 18:17:12

标签: sql sql-server tsql

我有一个包含这些值的表

create table LoanExample (
        LoanId int,
        ConstraintId int,
        BorrowerName varchar(128));

    insert into LoanExample values (1, null, 'Jack')
    insert into LoanExample values (1, 33, 'July')
    insert into LoanExample values (2, 78, 'Mike')
    insert into LoanExample values (2, 72, 'Wayne')
    insert into LoanExample values (3, null, 'David')
    insert into LoanExample values (3, 79, 'Chris')
    insert into LoanExample values (4, null, 'Finn')
    insert into LoanExample values (4, null, 'James')

我希望计算每个LoanId的约束,即使其值为null,并将其添加到临时表中。

我尝试过

    select 
        LoanId,
        Constraints_Count = count(ConstraintId)
    into #Test
    from LoanExample
    group by LoanId

但是此查询将忽略count函数中的所有空值,并向我显示警告消息“警告:通过聚合或其他SET操作消除了空值”。 !

我希望每个LoanId的Constraints_Count为'2',但是对于ConstraintId为空的LoanId,其Constraints_Count的值将减小。

因此,对于LoanId 1和3,我得到Constraints_Count为'1',但我希望为'2';对于LoanId 4,我为Constraints_Count得到了ROW_NUMBER()为'0',但我希望为'2'。

我想我可以使用addEvent=(index)=>{ this.setState({isModalOpen: true}) const copyWidgets=Object.assign([],this.state.widgets); let widget=this.state.widgets[index]; widget.content=<DataTable/>; //I would like to allow the user to choose from a list of components instead of just adding <DataTable/> copyWidgets[index]=widget; this.setState({ widgets:copyWidgets }) } ,但我不确定如何使用。

5 个答案:

答案 0 :(得分:3)

仅使用count(*)或sum(1):

select 
    LoanId,
    Constraints_Count = count(*)
into #Test
from LoanExample
group by LoanId

select 
    LoanId,
    Constraints_Count = sum(1)
into #Test
from LoanExample
group by LoanId

答案 1 :(得分:1)

根据您的DBMS,您可以将null转换为0。

SQL Server:

select 
        LoanId,
        Constraints_Count = count(isnull(ConstraintId,0))
    into #Test
    from LoanExample
    group by LoanId

Oracle:

select 
        LoanId,
        Constraints_Count = count(nvl(ConstraintId,0))
    into #Test
    from LoanExample
    group by LoanId

其他:

select 
        LoanId,
        Constraints_Count = count(case when ConstraintId is null then 0 else ConstraintId end))
    into #Test
    from LoanExample
    group by LoanId

答案 2 :(得分:0)

相反,使用coalesce()会将空值转换为有效的整数值:

Constraints_Count = count(coalesce(ConstraintId,1))

在您的情况下,我使用的值1无关紧要。它可以是任何其他整数值。

答案 3 :(得分:0)

count()处理空值,因此您可以尝试使用大小写反转空值

select 
    LoanId,
    count(case when ConstraintId is null then 1 else null)  Constraints_Count
from LoanExample
group by LoanId

答案 4 :(得分:0)

尝试以下情况,如下尝试

    select 
    LoanId,
    Constraints_Count = sum(case when ConstraintId is null then 1 else 1 end)
into #Test
from LoanExample
group by LoanId