sql >> Databasteknik >  >> RDS >> Sqlserver

Hur räknar man i SQL alla fält med nollvärden i en post?

declare @T table
(
  ID int,
  Name varchar(10),
  Age int,
  City varchar(10),
  Zip varchar(10)
)  

insert into @T values 
(1, 'Alex', 32, 'Miami', NULL),
(2,  NULL,  24,  NULL,   NULL)

;with xmlnamespaces('http://www.w3.org/2001/XMLSchema-instance' as ns)
select ID,
       (
          select *
          from @T as T2
          where T1.ID = T2.ID
          for xml path('row'), elements xsinil, type 
       ).value('count(/row/*[@ns:nil = "true"])', 'int') as NullCount
from @T as T1

Resultat:

ID          NullCount
----------- -----------
1           1
2           3

Uppdatering:

Här är en bättre version. Tack till Martin Smith .

;with xmlnamespaces('http://www.w3.org/2001/XMLSchema-instance' as ns)
select ID,
       (
          select T1.*
          for xml path('row'), elements xsinil, type 
       ).value('count(/row/*[@ns:nil = "true"])', 'int') as NullCount
from @T as T1

Uppdatering:

Och med lite snabbare XQuery-uttryck.

;with xmlnamespaces('http://www.w3.org/2001/XMLSchema-instance' as ns)
select ID,
       (
          select T1.*
          for xml path('row'), elements xsinil, type 
       ).value('count(//*/@ns:nil)', 'int') as NullCount
from @T as T1


  1. SCD typ 4

  2. LongOpsWatcher i SQL Dev

  3. Hur ansluter jag till MySQL Database?

  4. java.net.ConnectException:misslyckades med att ansluta till localhost/127.0.0.1 (port 80):anslutning misslyckades:ECONNREFUSED (Anslutning nekades)