简体   繁体   中英

Merge 2 rows in SQL Server

In table or some result of JOIN exists 2 rows with same Email but has different other values.

Example:

Email          -/- Operation1 (BIT) -/- Operation2 (BIT)
test@email.com -/- 1          -/- 0
test@email.com -/- 0          -/- 1

How can I group rows by Email and select them in next format (according to sample)

Email          -/- Operation1 (BIT) -/- Operation2 (BIT)
test@email.com -/- 1          -/- 1

If Operation1 is TRUE in one row then in result return TRUE

As mentioned in your table for Bit Fields the below query will work in SQL SERVER 2008

CREATE TABLE #temp
(
email VARCHAR(30),
Operation1 BIT,
Operation2 BIT
)

INSERT INTO #temp VALUES('test@email.com',1,0)
INSERT INTO #temp VALUES('test@email.com',0,1)

-- METHOD 1
SELECT email,
MAX(CASE WHEN Operation1 = 1 THEN 1 ELSE 0 END) AS Operation1,
MAX(CASE WHEN Operation2 = 1 THEN 1 ELSE 0 END) AS Operation2
FROM #temp GROUP BY email

-- METHOD 2
SELECT email,MAX(CONVERT(INT,Operation1)) AS Operation1,
MAX(CONVERT(INT,Operation2)) AS Operation2
FROM #temp GROUP BY email


--DROP TABLE #TEMP

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