1

我有两张桌子:

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 将是:

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 不是唯一的。

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

4

1 回答 1

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 演示- 我在 TableC 中添加了一行以检查它是否包含它

于 2013-08-12T19:06:53.997 回答