简体   繁体   中英

Different rows for results while using the SQL case statement for same value

The result should be in a single row with logged in and not logged in counts. Why it is coming in two different rows for same account?

SELECT distinct  Account
     , SUM(CASE Val WHEN status='logged in' THEN  1 Else 0  END) AS 'Total logged in' 
     , SUM(CASE Val WHEN status='not logged in' THEN  1 Else 0 END) AS 'total not logged in '
FROM TableAccount 
GROUP BY Account

account    logged in    not logged in
A            21             0
A            0              2

This seems to be giving the result as desired if your table structure is same.

create table test1(col1 varchar(10), col2 varchar(10))

insert into test1
values('A','L'),
('A','NL'),
('A','L'),
('A','L')

SELECT distinct  col1
     , SUM(CASE WHEN col2='L' THEN  1 Else 0  END) AS 'Total logged in' 
     , SUM(CASE WHEN col2='NL' THEN  1 Else 0 END) AS 'total not logged in '
FROM test1 
GROUP BY col1

SELECT DISTINCT is almost never needed with GROUP BY . Also, you are correct, there should only be one row for 'A' -- assuming the account is exactly the same.

The fact that you are getting two rows means that they are not the same. One issue could be trailing blanks. You can check for this:

SELECT DISTINCT '|' +  Account + '|'
FROM TableAccount ;

Other problems could be characters that look the same or hidden characters. Finding the problem might require some investigation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM