基于使用sql变量的不一致的结果

时间:2017-11-21 12:18:13

标签: sql sql-server variables join

我不明白查询的结果...... 结果使用不同的连接和声明的变量或costants进行更改。

发生了什么?

declare @inserted table
(id              int,
 tnumber         nvarchar(50),
 id_prod_inesito int
);

insert into @inserted
values
(41649,'0438492300',172400);

select pic.ID
      ,PIC.ID_PROD_INESITO
      ,pic.NUMERO_TELEFONO
      ,pic.IS_REQUESTED
      ,ins.*
      ,min(pic.id) over(partition by pic.numero_telefono) as min_id
from prod_ivr_call as pic
    inner join prod_inesito as pin
        on pic.ID_PROD_INESITO = pin.ID
    left join @inserted as ins
        on ins.ID_PROD_INESITO = pin.ID
where pic.is_requested = 0;

enter image description here

如果我在内连接中更改连接

select pic.ID
      ,PIC.ID_PROD_INESITO
      ,pic.NUMERO_TELEFONO
      ,pic.IS_REQUESTED
      ,ins.*
      ,min(pic.id) over(partition by pic.numero_telefono) as min_id
from prod_ivr_call as pic
    inner join prod_inesito as pin
        on pic.ID_PROD_INESITO = pin.ID
    join @inserted as ins
        on ins.ID_PROD_INESITO = pin.ID
where pic.is_requested = 0;

select pic.ID
      ,PIC.ID_PROD_INESITO
      ,pic.NUMERO_TELEFONO
      ,pic.IS_REQUESTED
      ,ins.*
      ,min(pic.id) over(partition by pic.numero_telefono) as min_id
from prod_ivr_call as pic
    inner join prod_inesito as pin
        on pic.ID_PROD_INESITO = pin.ID
    left join @inserted as ins
        on ins.ID_PROD_INESITO = pin.ID
where pic.is_requested = 0
      and ins.id is not null;

enter image description here

改为写

select pic.ID
      ,PIC.ID_PROD_INESITO
      ,pic.NUMERO_TELEFONO
      ,pic.IS_REQUESTED
      ,ins.*
      ,min(pic.id) over(partition by pic.numero_telefono) as min_id
from prod_ivr_call as pic
    inner join prod_inesito as pin
        on pic.ID_PROD_INESITO = pin.ID
    left join @inserted as ins
        on ins.ID_PROD_INESITO = pin.ID
where pic.is_requested = 0
      and numero_telefono = '0438492300';

enter image description here

最后写作

select pic.ID
      ,PIC.ID_PROD_INESITO
      ,pic.NUMERO_TELEFONO
      ,pic.IS_REQUESTED
      ,ins.*
      ,min(pic.id) over(partition by pic.numero_telefono) as min_id
from prod_ivr_call as pic
    inner join prod_inesito as pin
        on pic.ID_PROD_INESITO = pin.ID
    left join @inserted as ins
        on ins.ID_PROD_INESITO = pin.ID
where pic.is_requested = 0
      and numero_telefono = ins.tnumber;

enter image description here

1 个答案:

答案 0 :(得分:1)

当然会改变。

您正在从查询返回的值列表中找到min prod_ivr_call.id值,而不是整个表格。通过添加从此表中删除不匹配值的其他过滤器(即:@inserted.idnull),min值将不同。

这里发生的事情是你误解了窗口函数的工作原理。