How to join two rows into just one in SQL Server

How to join two rows into just one in SQL Server



I'm trying to write a SQL query where the idea is to join two rows into one.
When performing


select * from caixa



I get the following result:


id money open closed fun type situation
--------------------------------------------------------------------
13 10 08/09/2018 18:55 1 E 1
37 -473 09/09/2018 17:01 1 F 1
40 0 09/09/2018 17:08 1 E 2
41 0 10/09/2018 17:09 1 F 2



The idea is to join the two rows where the situations are the same
getting for example:


money open closed fun type situation
--------------------------------------------------------------------
-473 08/09/2018 18:55 09/09/2018 17:01 1 E 1






You need to specify how to aggregate the other columns (money, fun and type) when grouping by situation.

– Wolfgang Kais
Sep 9 '18 at 22:17


money


fun


type


situation






will you have more than 1 rows with same situation value ?

– Squirrel
Sep 10 '18 at 1:23


situation




2 Answers
2



You can try to use aggregate function to make it


SELECT MIN(money) as money ,MAX(open) as open,
MAX(closed) as closed,fun,MIN(type) as type,
MIN(situation) as situation
FROM caixa
GROUP BY fun






this even works, but I did not want to compare the date with max, I would have to do something to get it if it is different from empty ?

– Emiry Mirella
Sep 9 '18 at 20:43






What will you want to do if there are many different dates? MAX can filter the empty string or NULL then get the values

– D-Shih
Sep 9 '18 at 20:50



MAX


NULL



Try joining the table with itself


SELECT O.money as open_money, C.money as closed_money,
O.open as open, C.closed as closed,
O.fun as open_fun, C.fun as closed_fun,
O.type as open_type, C.type as closed_type
FROM caixa O, caixa C
WHERE O.id <> C.id
AND O.situation = C.situation
AND O.open IS NOT NULL
AND C.closed IS NOT NULL



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế