I'm working on GCP and I've this table below:
Name | B | C | same | different |
---|---|---|---|---|
Arun | 1234-5678 | 1234 | 1 | 0 |
Tara | 6789 - 7654 | 6789 | 1 | 0 |
Arun | 4567 | 4324 | 0 | 1 |
Here, I have compared B
and C
columns by taking the first 4 digits.
If B and C are same then '1' should come in another column I've created - Same
IF B and C are not same then, '1' should come in another column I've created - Different
Now, I want to find the count of same and different for each Name
.
If count(same) > 1 then, '1' should come in another column 'YES', which we have to create
If count(different)> 1 then '1' should come in another columns 'NO' else 0 in all cases.
Basically, For Arun
, Yes and No columns should come as 1.
So far I've tried this:
SELECT
Name,B, C,
CASE WHEN SUBSTRING_INDEX(B, "-", 1) = C THEN 1 ELSE 0 END as same,
CASE WHEN SUBSTRING_INDEX(B, "-", 1) <> C THEN 1 ELSE 0 END as different,
SUM(CASE WHEN SUBSTRING_INDEX(B, "-", 1) = C THEN 1 ELSE 0 END) as total_same,
SUM(CASE WHEN SUBSTRING_INDEX(B, "-", 1) <> C THEN 1 ELSE 0 END) as total_different,
IF(SUM(CASE WHEN SUBSTRING_INDEX(B, "-", 1) = C THEN 1 ELSE 0 END) >1) 1, 0 as YES,
IF(SUM(CASE WHEN SUBSTRING_INDEX(B, "-", 1) <> C THEN 1 ELSE 0 END) >1) 1, 0 as NO
FROM
Users
GROUP BY Name,B,C
Expected output:
Name | B | C | count(same) | count(different) | yes | no |
---|---|---|---|---|---|---|
Arun | 1234-5678 | 1234 | 1 | 1 | 1 | 1 |
Tara | 6789 - 7654 | 6789 | 1 | 0 | 1 | 0 |
But it is not working. Can anyone please help?