Question

I have a join query which returns multiple rows

ID    SearchID   Bool1      Bool2    Bool2
1     1          1          1        0
1     1          0          0        0
5     1          1          0        0
6     1          0          0        0
9     1          0          0        0

The first column ID can be omitted, which leaves us with

SearchID   Bool1      Bool2    Bool2
1          1          1        0
1          0          0        0
1          1          0        0
1          0          0        0
1          0          0        0

Since all the data returned applies to SearchID 1, I would like to end up with a row that will merge the results of all the boolean fields i.e.

SearchID   Bool1      Bool2    Bool2
1          1          1        0

IsButton should be 1 as there was one or more row with 1 AutoRun should be 1 as there was one or more row with 1 IsOnMain should be 0 as there was no rows with 1

but I want handle this for multiple rows that may have been returned and I want to end up with a unique row for each searchid

ID    SearchID   Bool1      Bool2    Bool2
1     1          1          1        0
1     1          0          0        0
5     1          1          0        0
6     1          0          0        0
9     1          0          0        0
3     2          0          0        0
5     2          0          0        0
3     3          0          0        0
9     3          0          0        1
etc...

SearchID   Bool1      Bool2    Bool2
1          1          1        0
2          0          0        0
3          0          0        1
etc...

Am I making sense?

Was it helpful?

Solution

SELECT SearchID, 
       CAST(CASE WHEN SUM(CAST(Bool1 AS INT)) > 0 THEN 1 ELSE 0 END AS BIT) AS Bool1,
       CAST(CASE WHEN SUM(CAST(Bool2 AS INT)) > 0 THEN 1 ELSE 0 END AS BIT) AS Bool2,
       CAST(CASE WHEN SUM(CAST(Bool3 AS INT)) > 0 THEN 1 ELSE 0 END AS BIT) AS Bool3
FROM Table
GROUP BY SearchID

OTHER TIPS

SELECT SearchId
     , MAX(CAST(Bool1 AS INT)) AS Bool1
     , MAX(CAST(Bool2 AS INT)) AS Bool2
     , MAX(CAST(Bool3 AS INT)) AS Bool3
FROM TableX
GROUP BY SearchId

If you are using a BIT data type then you can't make use of SUM or MAX function on it directly. You have to convert it first.

--Sample table
CREATE TABLE #test
(
    SearchID INT, 
    Bool1 BIT, 
    Bool2 BIT, 
    Bool3 BIT
)
GO

INSERT #test VALUES (1,1,1,0)
INSERT #test VALUES (1,0,0,0)
INSERT #test VALUES (1,1,0,0)
INSERT #test VALUES (1,0,0,0)
INSERT #test VALUES (1,0,0,0)
Go

 SELECT 
    SearchId
    ,MAX(CONVERT(INT,Bool1)) AS Bool1
    ,MAX(CONVERT(INT,Bool2)) AS Bool2
    ,MAX(CONVERT(INT,Bool3)) AS Bool3
FROM #test
GROUP BY SearchId
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top