Using CASE to create new column based on specific text in a string column

独自空忆成欢 提交于 2019-12-10 14:38:16

问题


I found a couple similar threads, but none are working. I'm trying to create a new column for when another column satisfies a certain condition.

This is the code I'm working with:

SELECT DISTINCT R.[Column1] AS Person, 
SUM(CASE WHEN  R.[Event] = 'Event1' THEN 1 ELSE NULL END) AS Event1,
    CASE (WHEN L.[Column2] LIKE '%String1%' THEN 'String1'
        ELSE WHEN L.[Column2] LIKE '%String2%' THEN 'String2'
        ELSE WHEN L.[Column2] LIKE '%String3%' THEN 'String3'
        ELSE NULL END) AS NewColumn
  FROM [Database1].[dbo].[Table1] R
  LEFT JOIN
     [Database1].[dbo].[Table2] L
        ON R.[UniqueIdentifier] = L.[UniqueIdentifier]
    WHERE L.[Column2] LIKE '%String1%'
        OR L.[Column2] LIKE '%String2%'
        OR L.[Column2] LIKE '%String3%'
GROUP BY  R.[Column1], L.[Column2]
ORDER BY R.[Event1] DESC

If I take the CASE statements from column 2 out, then the query works fine. My desired results are three columns: Person, String, Event... counting Events with an aggregation on Person and String.

The error is: Msg 156, Level 15, State 1, Line 3 Incorrect syntax near the keyword 'CASE'.


回答1:


You had some syntax issues:

1st issue was: CASE (WHEN

2nd issue was: ELSE WHEN

This should run fine now:

SELECT DISTINCT
       R.[Column1] AS Person,
       SUM(CASE
               WHEN R.[Event] = 'Event1'
               THEN 1
               ELSE NULL
           END) AS Event1,
       (CASE
            WHEN L.[Column2] LIKE '%String1%'
            THEN 'String1'
            WHEN L.[Column2] LIKE '%String2%'
            THEN 'String2'
            WHEN L.[Column2] LIKE '%String3%'
            THEN 'String3'
            ELSE NULL
        END) AS NewColumn
FROM [Database1].[dbo].[Table1] R
     LEFT JOIN [Database1].[dbo].[Table2] L ON R.[UniqueIdentifier] = L.[UniqueIdentifier]
WHERE L.[Column2] LIKE '%String1%'
      OR L.[Column2] LIKE '%String2%'
      OR L.[Column2] LIKE '%String3%'
GROUP BY R.[Column1],
         L.[Column2]
ORDER BY R.[Event1] DESC;


来源:https://stackoverflow.com/questions/45018423/using-case-to-create-new-column-based-on-specific-text-in-a-string-column

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