Table: I have a database table table_name2 in SQL Server 2012 with data as:
col1 col2 col3
one first abc-3ab9-cd-f-01
two second abcdefg04
three first
three second mnopqrs03
one first NULL
two first 'NULL'
one second papapap
two second dbrf434
two first 434jhpo
DDL: And created it using
CREATE TABLE [dbo].[table_name2](
[col1] [nvarchar](255) NULL,
[col2] [nvarchar](255) NULL,
[col3] [nvarchar](255) NULL
) ON [PRIMARY];
Data populated:
insert into table_name2
values ('one','first','abc-3ab9-cd-f-01'),
('two','second','abcdefg04'),
('three','first',''),
('three','second','mnopqrs03'),
('one','first',NULL),
('two','first','NULL'),
('one','second','papapap'),
('two','second','dbrf434'),
('two','first','434jhpo');
I want to list each combination of col1 and col2. Then count of col3 for each of this col1/col2 combination where col3 is either blank, 'N/A', NULL or 'NULL'.
For those combinations of col1/col2 where none of the conditions related to col3 are met, I want to show 0 for those combinations.
My desired result is:
col1 col2 MainCount
one first 1
one second 0
three first 1
three second 0
two first 1
two second 0
What I have tried: For now I have tried a simple query and two modified versions of it
SELECT col1, col2, count(col3) as MainCount
FROM table_name2
WHERE col3 is null OR col3 = '' OR col3 = 'N/A' OR col3 = 'Unknown' OR col3 = 'NULL'
GROUP BY col1, col2
ORDER BY col1, col2;
Gives:
col1 col2 MainCount
one first 0
three first 1
two first 1
Then
SELECT col1, col2, count(col3) as MainCount
FROM table_name2
WHERE col3 =
CASE WHEN
(col3 is null OR col3 = '' OR col3 = 'N/A' OR col3 = 'Unknown' OR col3 = 'NULL')
THEN col3 ELSE NULL
END
GROUP BY col1, col2
ORDER BY col1, col2;
Gives:
col1 col2 MainCount
three first 1
two first 1
And last one
SELECT col1, col2, count(CASE WHEN col3 is not null THEN col3 ELSE 0 END) as MainCount
FROM table_name2
WHERE col3 is null OR col3 = '' OR col3 = 'N/A' OR col3 = 'Unknown' OR col3 = 'NULL'
GROUP BY col1, col2
ORDER BY col1, col2;
Gives error as:
Conversion failed when converting the nvarchar value 'NULL' to data type int.
What am I doing wrong here and how can I get the desired output?