如何在我的查询中仅显示Y状态

时间:2016-02-04 20:52:15

标签: sql sql-server sql-server-2008

我想在一个字段中只显示一个状态:

select *, ROW_NUMBER() OVER(PARTITION BY t.Docentry ORDER BY t.linealog) FILA
from (select docnum, docentry,Confirmed as confirmado,UserSign2 as usuario,ObjType as tipodoc ,UpdateDate,UpdateTS as Hora,LogInstanc as linealog
from adoc
where ObjType=17
union all
select DocNum, DocEntry,Confirmed,UserSign2,ObjType,UpdateDate,UpdateTS,99 from ordr
) as t
order by DocEntry, FILA

这给我这个输出:

Output1

你可以在这种情况下看到ndoc 1:给我4行,我只想要2,只有Y,我这样做了:

with mycte as (

select *, ROW_NUMBER() OVER(PARTITION BY t.Docentry ORDER BY t.linealog) FILA
from (select docnum, docentry,Confirmed as confirmado,UserSign2 as usuario,ObjType as tipodoc ,docdate,UpdateDate,UpdateTS as Hora,LogInstanc as linealog
from adoc
where ObjType=17 
union all
select DocNum, DocEntry,Confirmed,UserSign2,ObjType,docdate,UpdateDate,UpdateTS,99 from ordr
) as t

),

mycte2 as (

select m.*, coalesce(m2.confirmado,'N') confirmadoanterior from mycte m left join mycte m2 on m.fila+1=m2.fila and m.fila=1 )

select * from mycte2 where confirmado='Y'  and confirmadoanterior='N'  

order by docnum 

我只想要状态为' Ÿ'来自地位' N'在这种情况下只有第10行。

这是预期的结果: expected result

我也采用什么方式过滤Y状态?

感谢。

1 个答案:

答案 0 :(得分:0)

在UNION ALL查询中尝试过滤[Confirmed] ='Y'。 e.g。

SELECT
      *
FROM (
      SELECT
            *
          , ROW_NUMBER() OVER (PARTITION BY t.Docentry ORDER BY t.linealog) FILA
      FROM (
            SELECT
                  docnum
                , docentry
                , Confirmed AS confirmado
                , UserSign2 AS usuario
                , ObjType AS tipodoc
                , docdate
                , UpdateDate
                , UpdateTS AS Hora
                , LogInstanc AS linealog
            FROM adoc
            WHERE ObjType = 17 AND Confirmed = 'Y' --<< HERE
            UNION ALL
                  SELECT
                        DocNum
                      , DocEntry
                      , Confirmed
                      , UserSign2
                      , ObjType
                      , docdate
                      , UpdateDate
                      , UpdateTS
                      , 99
                  FROM ordr
                  WHERE Confirmed = 'Y' --<< & HERE
            ) AS u
     ) AS d
ORDER BY
      docnum

如果这不是你想要的,请提供“样本数据”和“预期结果”。