【问题标题】:HOWTO: Include column that is not part of an aggregate function or Group by clause in SQL SERVER如何:在 SQL SERVER 中包含不属于聚合函数或 Group by 子句的列
【发布时间】:2017-06-15 15:29:03
【问题描述】:

我有以下递归 CTE:

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

所以现在我正在尝试在我的案例中做同样的事情,我正在尝试应用 John Woo 解决方案,但我不知道如何。有什么帮助吗?还是有其他最佳解决方案?

【问题讨论】:

  • 我已经回答了您提出的问题,但从您的测试数据来看,我认为这实际上并不是您想要做的。如果我下面的答案不是您想要做的,您能否提供您想要的输出?

标签: sql-server sql-server-2008 group-by sql-server-2008-r2 with-statement


【解决方案1】:

iamdave 是对的,但如果您想从链接的答案中实施 John Woo 的解决方案,它看起来像这样:

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

【讨论】:

    【解决方案2】:

    只需将最后一行更改为GROUP BY PARENT_TEST_ID, TEST_ID

    您遇到的错误是告诉您,如果您不对其进行聚合或按其对其他聚合进行分组,则无法将列添加到输出中。通过将列添加到 group by,您就是在告诉 SQL Server 您希望通过父 ID 值和测试 ID 值来执行 min

    rextester:http://rextester.com/JRF55398

    【讨论】:

      猜你喜欢
      • 2013-02-10
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多