SQL Server查询从每个子组中选择1

时间:2011-06-06 22:07:30

标签: sql-server tsql sql-server-2008

我有一组数据,需要为每个CON / OWNER / METHOD / MATRIX集提取一条记录。如果存在非空结果,我想要那个。否则,我想要一个COUNT最高的那个。我如何查询?

CON      OWNER      METHOD      MATRIX  RESULT  COUNT
*CON_1   OWNER_1    METHOD_A    SOLID   NULL    503
CON_1    OWNER_1    METHOD_A    SOLID   NULL    1

*CON_1   OWNER_1    METHOD_A    SOIL    NULL    1305
CON_1    OWNER_1    METHOD_A    SOIL    NULL    699

*CON_2   OWNER_2    METHOD_B    SOLID   290     687
CON_2    OWNER_2    METHOD_B    SOLID   NULL    NULL
CON_2    OWNER_2    METHOD_B    SOLID   450     600

CON_2    OWNER_2    METHOD_B    WATER   NULL    1
*CON_2   OWNER_2    METHOD_B    WATER   400     NULL

对于结果,我想只显示已加星标的记录,并且我将展示每个组的分组方式。

这是错误的SQL:

select top (1) CON, OWNER, METHOD, MATRIX, RESULT, COUNT
from #TempTable
group by CON, OWNER, METHOD, MATRIX
order by CON, OWNER, METHOD, MATRIX, COUNT

...因为我的计数不是聚合函数的一部分。它也不处理RESULT为NULL,并且top(1)不会从每个分组返回1。但是,使用更复杂的查询(例如基于How can I select multiple columns from a subquery (in SQL Server) that should have one record (select top 1) for each record in the main query?的问题)我没有进一步了解

如何从每个分组中选择一个?

3 个答案:

答案 0 :(得分:11)

试试这个,不是100%确定语法是正确的,但它很接近。

select 
    * 
from
    (select
        CON,
        OWNER,
        METHOD,
        MATRIX,
        RESULT,
        COUNT,
        RANK() OVER(PARTITION BY CON, OWNER, METHOD,MATRIX ORDER BY RESULT,COUNT DESC) as rnk
    FROM #TempTable
) a
WHERE rnk = 1

答案 1 :(得分:2)

在支持窗口的RDBMS中(包括SQL Server 2008,我相信)

SELECT CON, OWNER, METHOD, MATRIX, RESULT, `COUNT`
FROM
 (SELECT CON, OWNER, METHOD, MATRIX, RESULT, `COUNT`, 
  RANK() OVER (PARTITION BY CON, OWNER, METHOD, MATRIX
               ORDER BY RESULT DESC, `COUNT` DESC) AS rk
  FROM temptable
 ) AS s
WHERE rk=1;

请注意,您的文本仅表示每个组只有一个非空结果,但您的示例却没有。此版本将选择最大结果,除非count将成为决胜局时所有结果都相同(例如,NULL)。顺便说一句,COUNT作为一个列名会引起各种各样的悲痛。如果结果和计数都有关联,则此版本还会选择多行。无论是否存在平局,都将排名切换为row_number以获得一个。

答案 2 :(得分:0)

select DetailID, field2, field3, field4, MasterID 
from table outer
where DetailID= 
    (
        select max(DetailID) 
        From table inner 
        where outer.MasterID = inner.MasterID
        group by MasterID 
    )

您可以将其用作视图并加入。