简体   繁体   English

SQL 除运算符和 CTE 选择第一个查询中的所有项目但不在第二个查询中

[英]SQL Except Operator and with CTE to select all the items in 1st query but not in 2nd Query

I am trying to get all the data in the 1st query below but except the data from the 2nd query below.我试图获取下面第一个查询中的所有数据,但下面第二个查询中的数据除外。

Here 1st I am trying to select the unique data/distinct data by using with cte and partition by .在这里 1st 我试图通过使用with ctepartition by来选择唯一数据/不同数据。

I tried using except, but I get this error:我尝试使用except,但出现此错误:

Incorrect syntax near the keyword 'with'.关键字“with”附近的语法不正确。 If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.***如果此语句是公用表表达式、xmlnamespaces 子句或更改跟踪上下文子句,则前一条语句必须以分号结束。***

First query:

    With cte as
    (
        select 
            *, 
            row_number() over (partition by [Employee ID] order by [QTR] DESC, Wk desc) rownumber 
        from 
            tbl_HC
    )
    select * 
    from cte 
    where rownumber = 1
      and QTR = (Select max(QTR) from tbl_HC)

    Except

    --2nd query
    With cte as
    (
         select 
             *, 
             row_number() over (partition by [Employee ID] order by [QTR] DESC, Wk desc) rownumber 
         from  
             tbl_HC
    )
    select * 
    from cte 
    where rownumber = 1
        and Wk= (
        Select max(Wk) from tbl_HC
        where QTR = (Select max(QTR) from tbl_HC))`

your query would be like below您的查询如下所示

With cte as
    (select *, row_number() 
    over(partition by [Employee ID] order by [QTR] DESC,Wk DESC) rownumber 
    from tbl_HC
    ), cte1 as 
    (
     select *, row_number() 
    over(partition by [Employee ID] order by [QTR] DESC,Wk DESC) rownumber 
    from tbl_HC
    )
    select * from cte 
    where rownumber =1
    and QTR= (Select max(QTR) from tbl_SDS_Headcount_Manageby)
    except

    select * from cte1
    where rownumber =1
    and Wk= (
    Select max(Wk) from tbl_HC
    where QTR = (Select max(QTR) from tbl_HC))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM