我找到了几个类似的线程,但没有一个正在工作。我正在尝试为另一列满足某个条件时创建一个新列。
这是我正在使用的代码:
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'。
答案 0 :(得分:3)
您遇到了一些语法问题:
第一期是:CASE (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;