在两个不同的条件中查询同一表中同一字段的多个列

时间:2015-01-19 07:59:17

标签: mysql sql

此tblName表有4列{Date},{Status},{Meal},{Type} 我想在副子查询中使用条件来显示在不同的列中

Select Date, Status, Meal
    (Select Type as Special
     from tblName
     where Type In ('SSS','MMM')),
    (Select Type as Normal
     from tblName
     where Type Not IN ('SSS','MMM'))
From tblName

我收到错误消息

Msg 512, Level 16, State 1, Line 1
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

2 个答案:

答案 0 :(得分:0)

可能是这样的东西:

Select t1.Date, t1.Status, t1.Meal
    (t2.Type as Special),
    (t3.Type as Normal )
From tblName t1 LEFT JOIN
tblName t2
ON t1.ID=t2.ID
LEFT JOIN 
tblName t3
ON t1.ID=t3.ID
where t2.Type Not In ('SSS','MMM') 
OR t3.Type In ('SSS','MMM') 

OR

条件聚合

Select Date, Status, Meal
    (case when Type IN ('SSS','MMM') then Type else null end case) 
     )Type as Special,
   (case when Type NOT IN ('SSS','MMM') then Type else null end case) 
     )Type as Normal
From tblName

答案 1 :(得分:0)

您正在做的是:对于tblName中的每条记录,从tblName中选择所有类型,其中包含类型(&#39; SSS&#39;,&#39; MMM&#39;)。并且所有这些类型都应在tblName的结果行中显示为一列。当然,这不起作用。您可以做的是为tblName中的每条记录选择一个值。例如max(type)

然而,似乎你真正想要的只是展示特别的&#39;当类型是&#39; SSS&#39;或者&#39; MMM&#39;并且&#39;正常&#39;否则?

Select Date, Status, Meal,
  case when Type In ('SSS','MMM') then 'special' als 'normal' end as kind
From tblName;

或者在两个单独的列中显示类型?

Select Date, Status, Meal,
  case when Type In ('SSS','MMM') then Type end as Special,
  case when Type Not In ('SSS','MMM') then Type end as Normal
From tblName;
相关问题