Sql server在when语句中显示字符串
我有以下疑问Sql server在when语句中显示字符串,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,我有以下疑问 select (case when object like'%service%' then (object) when class like '%service%' then (class)end) From db group by (case when object like '%service%' then object when object_class like '%service%' then object_class
select (case
when object like'%service%' then (object)
when class like '%service%' then (class)end) From db group by (case when object like '%service%' then object
when object_class like '%service%' then object_class end)
这个查询检查每一列的值是否包含“service”而不是显示数据,我需要的不是只显示数据,而是显示数据和字符串
例如,当对象像“%service%”时,对象是“string”
字符串将是一个变量,在结果时存储在未知列中
第1栏第2栏
对象1 mystring
对象2 mystring
对象3 mystring
CASE语句只返回一个值-不能使用它返回多个列
您可以在每列中重复case语句:
select
case
when object like '%service%' then object
when class like '%service%' then class
end as column1,
case
when object like '%service%' then 'string'
when class like '%service%' then 'string'
end as column2
FROM ...
或者做一个工会:
请注意,如果存在对象和类都包含字符串服务的任何记录,则结果将不同。UNION将返回两条记录,大小写只会首先包含一个对象匹配。因此,如果其中一列包含单词“service”,则将第一个匹配显示为column1。您希望在第2列中显示“字符串”,以防在第1列中显示某些内容 编辑:我在第1列添加了一个GROUPBY子句,向您展示如何在此处进行聚合:
select
column1,
case when column1 is not null then 'string' end as column2,
min(some_other_column)
from
(
select
case
when object like '%service%' then object
when class like '%service%' then class
end as column1,
some_other_column
from mytable
) mydata
group by column1;
你能澄清一下吗?如果列包含“%service%”,那么您想在该列中显示该特定行的数据吗?是的,显示数据已经解决,但我需要显示数据和字符串,就像我们从…中选择对象“string”…一个CASE语句只能返回1列,您需要在单个列中返回数据和字符串吗,或者作为两个不同的专栏?两个不同的专栏我通过使用您的第一个答案并删除group by语句来解决这个问题,因为它是无用的
select
column1,
case when column1 is not null then 'string' end as column2,
min(some_other_column)
from
(
select
case
when object like '%service%' then object
when class like '%service%' then class
end as column1,
some_other_column
from mytable
) mydata
group by column1;