1

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.

I tried using except, but I get this error:

Incorrect syntax near the keyword '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.***

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))`
gulshan arora
  • 371
  • 1
  • 8
Punith GP
  • 690
  • 4
  • 11
  • 33
  • 1
    A `WITH` goes at the start of you statement, not the middle, and they need to have different names. If you need to declare 2 CTEs you need to do so at the start, I.e. `WITH CTE1 AS ({SELECT statement}), CTE2 AS ({SELECT statement}) SELECT * FROM CTE1 EXCEPT SELECT * FROM CTE2;` – Thom A Aug 06 '19 at 07:10
  • 1
    [WITH common_table_expression (Transact-SQL) - Using multiple CTE definitions in a single query](https://learn.microsoft.com/en-us/sql/t-sql/queries/with-common-table-expression-transact-sql?view=sql-server-2017#c-using-multiple-cte-definitions-in-a-single-query) – Thom A Aug 06 '19 at 07:11

1 Answers1

1

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))
Zaynul Abadin Tuhin
  • 31,407
  • 5
  • 33
  • 63