0

我有下面的递归CTE列:HOWTO:包括没有在SQL Server中的一个聚合函数或group by子句的一部分

DECLARE @T AS TABLE 
(
    PARENT_TEST_ID int, 
    TEST_ID int, 
    VALIDATED int, 
    ERR int 
) 

INSERT INTO @T VALUES 
(NULL, 1, 0, 0), 
(NULL, 2, 0, 0), 
(1,3,0, 0), 
(1,4,0, 0), 
(2,5,0, 0), 
(2,6,0, 0), 
(2,7,0, 0), 
(7,8,0, 1) 

;with C as 
(
    select TEST_ID, PARENT_TEST_ID, (CASE WHEN ERR=1 THEN 0 ELSE 1 END) AS VALIDATED, ERR 
    from @T 
    where TEST_ID not in (select PARENT_TEST_ID 
        from @T 
        where PARENT_TEST_ID is not null) AND PARENT_TEST_ID IS NOT NULL 
    union all 
    select 
    T.TEST_ID, 
    T.PARENT_TEST_ID, 
    (case when t.TEST_ID=c.PARENT_TEST_ID and c.VALIDATED=1 AND T.ERR=0 THEN 1 ELSE 0 END) as VALIDATED, 
    T.ERR 
    from @T as T 
    inner join C 
     on T.TEST_ID = C.PARENT_TEST_ID 
) 
SELECT DISTINCT PARENT_TEST_ID, TEST_ID, MIN(VALIDATED) FROM C 
GROUP BY TEST_ID 

但我不能包括在结果SELECT PARENT_TEST_ID列,因为它不是一部分GROUP BY子句的,所以我发现这个链接:

Including column that is not part of the group by

所以现在我试图做同样的在我的情况,我想申请吴宇森解决方案,但我不知道怎么办。任何帮助?还是其他的最佳解决方案?

+0

我有给你一个你已经问过的问题的答案,但是从你的测试数据来看,我并不认为它实际上是你想要做的。如果我的回答不是你想要做的,你能否请你包括你想要的输出? – iamdave

回答

0

你的最后一行就变成GROUP BY PARENT_TEST_ID, TEST_ID

你正在告诉你,你不能将列添加到输出的错误,如果你用它做的也不骨料上或组的其他聚集。通过将该列添加到group by,您告诉SQL Server您想通过父代和测试ID值执行min

rextester:http://rextester.com/JRF55398

0

iamdave是正确的,但如果你想实现从链接答案吴宇森的解决方案,它应该是这样的:

rextester:http://rextester.com/QQQGM79701

;with C as (
    select 
    test_id 
    , parent_test_id 
    , validated=(case when err = 1 then 0 else 1 end) 
    , err 
    from @T as t 
    where t.test_id not in (
    select i.parent_test_id 
    from @T as i 
    where i.parent_test_id is not null 
    ) 
    and t.parent_test_id is not null 
    union all 
    select 
    t.test_id 
    , t.parent_test_id 
    , validated = case 
     when t.test_id = c.parent_test_id 
     and c.validated = 1 
     and t.err = 0 
     then 1 
     else 0 
     end 
    , t.err 
    from @T as T 
    inner join c on t.test_id = c.parent_test_id 
) 
, r as (
    select 
    parent_test_id 
    , test_id 
    , Validated 
    , rn = row_number() over (
     partition by test_id 
     order by Validated 
    ) 
    from C 
) 
select 
    parent_test_id 
    , test_id 
    , Validated 
    from r 
    where rn=1 
相关问题