sql - Calculating Number of Columns that have no Null value -


i want make table following

| id | sibling1 |   sibling2 |   sibling 3  | total_siblings | ______________________________________________________________ | 1  |  tom     |    lisa    |    null      |       2        |  ______________________________________________________________ | 2  |  bart    |    jason   |    nelson    |       3        | ______________________________________________________________ | 3  |  george  |    null    |    null      |       1        | ______________________________________________________________ | 4  |  null    |    null    |    null      |       0        | 

for sibling1, sibling2, sibling3: nvarchar(50) (can't change requirement).

my concern how can calculate value total_siblings display number of siblings above, using sql? attempted use (sibling1 + sibling 2) not display result want.

cheers

a query trick.

select id,sibling1,sibling2,sibling3 ,count(sibling1)+count(sibling2)+count(sibling3) total mytable group id 

a little explanation required here. count field name count number of non-null values. since grouping id, ever return 0 or 1. now, if you're using other mysql, you'll have substitute

group id 

for

group id,sibling1,sibling2,sibling3 

because other databases require specify columns don't contain aggregate function in group section.

also, aside, may want consider changing database schema store siblings in table, each person can have number of siblings.


Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -