Skip to content
Advertisement

SQL Stored Procedures, Combining rows with derived variables

I’ve been away for sometime and need help with, what is probably a simple solution but at this time I’m stuck. I have this select statement and need to combine rows with like elements for the same department but the group by would have a very large select list, is there another way like MERGE? Here is the sql stmt I’m dealing with along with the output:

and the results:

These three rows need to be combined under the same department sorry if this is rather elementary but I’ve been out of this type of work for sometime now and need a refresher. Thanks

Advertisement

Answer

You want conitional aggregation. This works by creating a group by clause that contains all columns except those you want to merge, and then surround the conditional expression with an aggregate function (such as MIN() or MAX():

Side notes:

  • I rewrote the IIF() expressions to use CASE (the latter is standard SQL, while the former is TSQL-specific)

  • single quotes should be used for litteral strings, not for column identifiers (although SQL Server tolerates this)

  • you have multiple columns in the resultset that have the same name (time), this is not a good practice

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement