I'm not sure if there are neater methods, but this should work:
SELECT Field1, Field2, ISNULL(Field1) + ISNULL(Field2) Num_Null
FROM YourTable;
Test case:
CREATE TABLE YourTable (Field1 varchar(10), Field2 varchar(10));
INSERT INTO YourTable VALUES (NULL, 'A');
INSERT INTO YourTable VALUES ('B', 'C');
INSERT INTO YourTable VALUES ('B', NULL);
INSERT INTO YourTable VALUES (NULL, NULL);
Result:
+--------+--------+----------+
| Field1 | Field2 | Num_Null |
+--------+--------+----------+
| NULL | A | 1 |
| B | C | 0 |
| B | NULL | 1 |
| NULL | NULL | 2 |
+--------+--------+----------+
4 rows in set (0.00 sec)
UPDATE: Further to the updated question:
If you have columns in your table that look like affiliate_1
, affiliate_2
, etc, this is rarely a good idea as you would be mixing data with the metadata. In general, a recommended fix is to use another dependent table for the users-to-affiliates relationships, as in the following example:
CREATE TABLE users (
user_id int,
user_name varchar(100),
PRIMARY KEY (user_id)
) ENGINE=INNODB;
CREATE TABLE users_affiliates (
user_id int,
affiliate_name varchar(100),
PRIMARY KEY (user_id, affiliate_name),
FOREIGN KEY (user_id) REFERENCES users (user_id)
) ENGINE=INNODB;
Then sorting the users
table by the number of affiliates will look something like this:
SELECT u.*, d_tb.num_aff
FROM users
JOIN (
SELECT user_id, COUNT(*) num_aff
FROM users_affiliates
GROUP BY user_id
) d_tb ON (d_tb.user_id = u.user_id)
ORDER BY d_tb.num_aff DESC;
The advantages are plenty, but most importantly it makes queries such as the above easy to write, and flexible enough to work with any number of affiliates (an not limited by the number of columns you allocated).