有条件地从另一个表中选择其他行

时间:2013-08-12 18:56:22

标签: sql sql-server sql-server-2008 select case

我有两张桌子:

TableA
PK      Alpha    Critter   Etc 
1        A      zebra     apple
2        C      lion      orange
3        R      giraffe   banana
4        D      gopher    pear

TableC
PK      Alpha   Animal    Misc
1       D       beaver    kiwi
2       D       camel     avacado

我需要这个结果:

Result
PK      Alpha    Critter  Etc
22      A       zebra    apple
23      C       lion     orange
24      R       giraffe  banana
25      D       gopher   pear
26      D       beaver   kiwi
27      D       camel    avacado

如果TableA.Alpha的值等于多个具有相同值的TableC.Alpha 选择将是:

Select TA.Alpha, TA.Critter, TA.Etc
From TableA TA

Select TC.Alpha, TC.Animal, TC.Misc
From TableC TC

在不同的行上(上例中为3行)

否则只是

Select TA.Alpha, TA.Critter, TA.Etc
From TableA TA

(一行)

我可能会使用CTE。类似的东西:

With T_CTE (Alpha,CountAlpha)
AS
(SELECT 
TC. Alpha, COUNT(TC.Alpha) as CountAlpha
FROM TableC TC
GROUP BY TC.Alpha
HAVING (COUNT(TC.Alpha) > 1 ))

Select TA.Alpha, TA.Critter, TA.Etc
From TableA TA
case when T_CTE.Alpha is not null then...else...end
left join T_CTE on T_CTE.Alpha = TA.Alpha

TableA.Alpha是独一无二的。 TableC.Alpha不是唯一的。

我可以调用另一个add for addtional行吗?有更好的方法吗?我还想过创建临时表并从中进行选择。 这是一个更大的查询的一部分,但我现在要关注这一部分。 有什么建议? 感谢。

1 个答案:

答案 0 :(得分:1)

这样的东西
;with cte as (
  select A.Alpha, count(*) as cnt
  from TableA as A
      inner join TableC as C on C.Alpha = A.Alpha
  group by A.Alpha
  having count(*) > 1
)
select A.Alpha, A.Critter, A.Etc
from TableA as A
union all
select C.Alpha, C.Animal, C.Misc
from TableC as C
where C.Alpha in (select T.Alpha from cte as T)

sql fiddle demo - 已向Table添加一行以检查是否包含该行