JOIN两个SELECT语句结果

时间:2013-02-01 15:01:49

标签: sql select join

是否可以将2个sql SELECT语句的结果作为一个语句加入,其中两个查询相同的表,并在同一列中查找值?

我想要一个任务的id(这很好),但后来我想将某些值过滤成两个单独的列。

目前我分别得到2中的数据:

 SELECT id, string_value as Station FROM table WHERE datatype= 'station'

(不需要看到列数据类型)

返回类似的内容:

id            Station
task1         station1
task2         station2

然后我

SELECT id, string_value as RespondingAction FROM table 
 WHERE datatype='RespondingAction'

返回:

id             RespondingAction
task1          Approve
task2          Decline

我想基本上结合这两个查询,但我不确定他们是如何在同一列中查找数据。希望最终的结果是这样的:

id            Station           RespondingAction
task1         station1          Approve
task2         station2          Decline 
task3         station1          Decline
task4         station3          Pending (if null)

对不起,如果不太清楚;我是新手,并尽我所能来解决这个问题!

2 个答案:

答案 0 :(得分:1)

SELECT id, MAX(Station), NVL(Max(RespondingAction), 'Pending')
FROM
  (SELECT id, 
    string_value as Station,
    NULL as RespondingAction
   FROM table
   WHERE dataType = 'station'

   UNION

   SELECT id,
    NULL as Station,
    string_value as RespondingAction
   FROM table
   WHERE dataType = 'RespondingAction')
GROUP By id

修改

你也可以尝试替换

NVL(Max(RespondingAction), 'Pending')

通过

   COALESCE(MAX(RespondingAction), CAST('Pending' AS <the type of column string_value>))

答案 1 :(得分:1)

使用CASE

SELECT id, 
   case dataType when 'station' 
                 then string_value else 'Pending' end Station,
   case dataType when 'RespondingAction' 
                 then string_value else 'Pending' end RespondingAction
FROM table WHERE datatype IN ('station','RespondingAction')