Default comparison operand in SELECT WHERE condition

谁说胖子不能爱 提交于 2021-01-29 04:37:33

问题


I have a table CategoryColours, if a category is not found, it should return the colors from the default category "*".

Example if the table contains these lines:

Category  Color
*         white
*         black
1         red
1         blue
1         green
1         black

If I search the category "1", the query should get the 4 colors.

If I search the category "2", which has no records in the table, the query should get the 2 colors from the category "*".

Is it possible to use OpenSQL to get the exact list that I need in a single statement?

I tried with CASE and subqueries (EXIST) but I didn't manage.

It's not a stopper for my code, since I can just check if my category has records first or select my category + the default always and then remove the default if the other has records.


回答1:


I think you can use UNION. I didn't try code, it can include type errors.

SELECT
      category,
      color
    FROM CategoryColours
   WHERE category = lv_category
UNION
SELECT
  category,
  color
FROM CategoryColours
WHERE category eq '*'
 AND NOT EXISTS ( SELECT color 
                    FROM CategoryColours 
                   WHERE category = lv_category
                 )
INTO TABLE @DATA(lt_itab).


来源:https://stackoverflow.com/questions/58093569/default-comparison-operand-in-select-where-condition

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