用SQL Server组中没有的列选择

时间:2018-12-24 08:29:54

标签: sql sql-server

我要选择不在GROUP BY中的列。

我的代码:

 SELECT 
     dbo.func(field1, field2), field3
 FROM
     table
 WHERE
     field4 = 1224
 GROUP BY
     dbo.func(field1, field2), field3
 HAVING
     COUNT(id) > 1

我还要选择id列,如下所示:

 SELECT 
     id, dbo.func(field1, field2), field3
 FROM
     table
 WHERE
     field4 = 1224
 GROUP BY
     dbo.func(field1, field2), field3
 HAVING
     COUNT(id) > 1

2 个答案:

答案 0 :(得分:5)

我怀疑您要应用计数限制,然后返回原始表中的所有匹配记录以及标量函数的输出。一种方法是将COUNT用作分析函数,并具有与原始GROUP BY子句中出现的列相对应的分区。此处的区别在于,我们实际上并未汇总原始表。

WITH cte AS (
    SELECT id, dbo.func(field1, field2) AS out, field3,
        COUNT(id) OVER (PARTITION BY dbo.func(field1, field2), field3) cnt
    FROM yourTable
    WHERE field4 = 1224
)

SELECT id, out, field3
FROM cte
WHERE cnt > 1;

答案 1 :(得分:1)

您可以重新连接到原始表以检索ID为的匹配行:

SELECT  t.id
,       filter.funresult
,       t.field3
FROM    table t
JOIN    (
        SELECT  dbo.func(field1,field2) as funresult
        ,       field3
        FROM    table
        WHERE   field4 = 1224
        GROUP BY
                dbo.func(field1,field2)
        ,       field3
        HAVING  COUNT(id) > 1
        ) filter
ON      filter.funresult = dbo.func(t.field1, t.field2)
        AND filter.field3 = t.field3