How to get the result in below format in SQL Server?

GPK

I have a table called recipes with following data.

page_no title
-----------------
1       pancake
2       pizza
3       pasta
5       cookie

page_no 0 is always blank, and missing page_no are blank, I want output as below, for the blank page NULL values in the result.

left_title  right_title
------------------------
NULL           pancake
Pizza          pasta
NULL           cookie

I have tried this SQL statement, but it's not returning the desired output:

SELECT
    CASE WHEN id % 2 = 0 
            THEN title 
    END AS left_title,
    CASE WHEN id %2 != 0 
            THEN title 
    END AS right_title
FROM
    recipes
Gordon Linoff

You are quite close. You just need aggregation:

select max(case when id % 2 = 0 then title end) as left_title,
       max(case when id % 2 = 1 then title end) as right_title
from recipes
group by id / 2
order by min(id);

SQL Server does integer division, so id / 2 is always an integer.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related