从嵌套FROM

时间:2018-08-31 07:47:11

标签: sql sql-server

我试图像下面那样运行sth,但是在ID_period不是10的情况下,它会一直给我提供null'Value2'。我尝试了WITH子句,但是脚本太复杂了,无法提供多个选择从那开始。

示例:

SELECT Y.ID_period, Y.ID_country, Y.Value,
       (select Y.Value where ID_period = 10 and ID_country = Y.ID_country) as Value2
FROM (select A.ID_period, A.ID_country, A.Value
      from dbo.xyz as A) Y

感谢任何想法:)

3 个答案:

答案 0 :(得分:3)

我将其改写为自我加入:

SELECT
    t1.ID_period,
    t1.ID_country,
    t1.Value,
    COALESCE(t2.Value, 'NA') AS Value2
FROM dbo.xyz t1
LEFT JOIN dbo.xyz t2
    ON t1.ID_country = t2.ID_country AND t2.ID_period = 10;

答案 1 :(得分:1)

这是一种避免完全重新查询的假设,假设“ Period”提取子查询(A)会比完全重新查询便宜。如果不是这样,那么改进的可能性不大:

declare @t table (Period_ID int, Country varchar(10),Value int)
insert into @t(Period_ID,Country,Value) values
(0,'UK',0),(10,'UK',10),(20,'UK',20),(30,'UK',30)

select
    *
from (
select
    COALESCE(A.Period_ID,Y.Period_ID) as Period_ID,
    Y.Country,
    Y.Value,
    Z.Col
from
    (select * from @t) Y
        cross apply
    (select CASE WHEN y.Period_ID = 10 THEN 'Value2' ELSE 'Value1' END as Col) Z
        outer apply
    (select Period_ID from @t t where t.Country = Y.Country
     and Y.Period_ID = 10 and t.Period_ID != 10) A
) B
pivot (MAX(Value) for Col in (Value1,Value2)) C

结果:

Period_ID   Country    Value1      Value2
----------- ---------- ----------- -----------
0           UK         0           10
20          UK         20          10
30          UK         30          10

请注意,我排除了为 Period_ID生成的一行,因为我们仍未通过注释确定该行是否可取(如果确实如此,那肯定是还有更多工作要做

(如果您在t.Period_ID != 10中取出A过滤器,则会返回Period_ID 10的行,但其中{{1}有NULL }。我想我们可以再进一步Value来解决这个问题。

答案 2 :(得分:0)

自行退出加入可以帮助您

如果有特殊情况,可以使用子查询

  SELECT Y.ID_period, Y.ID_country, Y.Value, X.value as value2     
    FROM
    (
     select A.ID_period, A.ID_country, A.Value
     from dbo.xyz as A  // where condition
      ) Y
    left join
    (
    select A.ID_period, A.ID_country, A.Value
    from dbo.xyz   // where condition
    ) as x
      on  x.ID_country = Y.ID_country and x.ID_period=10

如果没有条件,那么简单的自我加入就能为您工作,@ Tim在回答中已经说过