我发现了几个类似的线程,但是都无法正常工作。我正在尝试为另一列满足特定条件的情况创建一个新列。
这是我正在使用的代码:
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
如果我从第2列中取出CASE语句,则查询工作正常。我希望得到的结果是三列:Person,String,Event …用Person和String的聚合计数事件。
错误是:消息156,级别15,状态1,第3行关键字’CASE’附近的语法不正确。
您有一些语法问题:
第一个问题是: CASE (WHEN
CASE (WHEN
第二个问题是: ELSE WHEN
ELSE WHEN
现在应该可以正常运行:
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;