如何根据Row_Number Over Partition by列从表中选择Row_Number Over Partition中的每个数据集?

时间:2016-10-05 08:46:11

标签: sql sql-server

如何根据Row_Number Over Partition by列从表中选择Row_Number Over Partition中的每个数据集?

请见下图:

Modifier Flags
The following constants (except for NSDeviceIndependentModifierFlagsMask)     represent device-independent bits found in event modifier flags:

Declaration
OBJECTIVE-C
enum {
   NSAlphaShiftKeyMask = 1 << 16,
   NSShiftKeyMask      = 1 << 17,
   NSControlKeyMask    = 1 << 18,
   NSAlternateKeyMask  = 1 << 19,
   NSCommandKeyMask    = 1 << 20,
   NSNumericPadKeyMask = 1 << 21,
   NSHelpKeyMask       = 1 << 22,
   NSFunctionKeyMask   = 1 << 23,
   NSDeviceIndependentModifierFlagsMask = 0xffff0000U 
};

我希望根据row_num列选择每个组中的每个数据集。

欢迎任何尝试。

3 个答案:

答案 0 :(得分:1)

虽然听起来你已经拥有ROW_NUMBER()专栏,但我相信这就是你所要求的。对于每个PACKAGENAME使用的第一条记录:

 SELECT s.* FROM (
     SELECT t.*,
            ROW_NUMBER() OVER(PARTITION BY t.packagename ORDER BY t.packageid) as rnk
     FROM YourTable t) s
WHERE s.rnk = 1

对于他们所有人都只使用内部查询。

答案 1 :(得分:0)

如果您想从每个组中获取单个记录,这是cte版本。

  ;with cte_1
   as(
     SELECT *,
            ROW_NUMBER() OVER(PARTITION BY [packagename],[package max units],  [references] ORDER BY [packageid]) as row_Numb 
     FROM YourTable ) 
   SELECT [packageid],[packagename],[package max units],[reference] 
   FROM cte_1
   WHERE row_Numb  = 1

答案 2 :(得分:0)

您可以使用TOP 1 WITH TIES并按ROW_NUMBER()订购:

SELECT TOP 1 WITH TIES *
FROM YourTable
ORDER BY ROW_NUMBER() OVER (PARTITION BY packagename ORDER BY packageid)

输出:

packageid   packagename package max units   references
44          Basic       10                  103
42          Cola        10                  102
2           Home        11                  101
1           Spicy       11                  104