case statement options splitted on two output columns

狂风中的少年 提交于 2020-05-17 06:14:05

问题


I have a table with a list of functionalities for my site. Say it has three columns:

id_usr - url - landing_page
1        a.php  a.html
2        b.php  b.html
3        c.php  c.html
4        d.php  d.html

Then I have a table where for each user i have those functionalities he can display:

id_usr - func
1         1
1         3

This query (from this question of mine)

SELECT    f.id, CASE WHEN id_user IS NOT NULL THEN url ELSE landing_page END
FROM      funzioni f
LEFT JOIN funz_abilitate fa ON fa.id_funzione = f.id AND fa.id_user = $id

is returning what is expected but the two options from the CASE statement are returned in one single column. Is it possible to split them in two columns (first for case url and second for case landing_page)?

Expected output is something like this

id_usr - case url - case landing_page
    1      a.php      NULL
    2      NULL       b.html
    3      c.php      NULL
    4      d.php      NULL

while actually it returns:

id_usr - case
    1    a.php
    2    b.html
    3    c.php
    4    d.php

回答1:


You need 2 CASE expressions:

SELECT    f.id, 
          CASE WHEN id_user IS NOT NULL THEN url END url,
          CASE WHEN id_user IS NULL THEN landing_page END landing_page
FROM      funzioni f
LEFT JOIN funz_abilitate fa ON fa.id_funzione = f.id AND fa.id_user = $id

Also you must qualify all the column names with the table's name/alias to avoid ambiguities.



来源:https://stackoverflow.com/questions/61755025/case-statement-options-splitted-on-two-output-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!