SQL Server:从前3个类别中选择前3个项

时间:2018-09-08 23:08:20

标签: sql sql-server

我正在尝试编写查询以接收来自前3个类别的前3个项目的单个数据集。

顶部类别将按按类别分组的ItemScore列的总和降序排列,例如,类别1的得分为23,类别2的得分为22。

该类别中的每个项目然后按其ItemScore降序排列。

这是原始数据的列表。

Raw Data (Image)

这是预期结果的一个例子。

Expected Result (Image)

我希望这有道理!

更新:

这是我一直在使用的脚本和一些测试数据;

CREATE TABLE [dbo].[Test]
(
    [CategoryID] [int] NULL,
    [CategoryName] [varchar](100) NULL,
    [ItemID] [int] NULL,
    [ItemName] [varchar](100) NULL,
    [ItemScore] [int] NULL
)

INSERT Test (CategoryID, CategoryName, ItemID, ItemName, ItemScore) 
VALUES (1, 'Category 1', 1, 'Item 1', 1),
       (1, 'Category 1', 2, 'Item 2', 2),
       (1, 'Category 1', 3, 'Item 3', 7),
       (1, 'Category 1', 4, 'Item 4', 1),
       (1, 'Category 1', 5, 'Item 5', 1),
       (2, 'Category 2', 6, 'Item 6', 1),
       (2, 'Category 2', 7, 'Item 7', 1),
       (2, 'Category 2', 8, 'Item 8', 9),
       (2, 'Category 2', 9, 'Item 9', 10),
       (2, 'Category 2', 10, 'Item 10', 2),
       (3, 'Category 3', 11, 'Item 11', 1),
       (3, 'Category 3', 12, 'Item 12', 1),
       (3, 'Category 3', 13, 'Item 13', 2), 
       (3, 'Category 3', 14, 'Item 14', 1),
       (3, 'Category 3', 15, 'Item 15', 2),
       (4, 'Category 4', 16, 'Item 16', 5),
       (4, 'Category 4', 17, 'Item 17', 6),
       (4, 'Category 4', 18, 'Item 18', 3),
       (4, 'Category 4', 19, 'Item 19', 5),
       (4, 'Category 4', 20, 'Item 20', 1),
       (5, 'Category 5', 21, 'Item 21', 2),
       (5, 'Category 5', 22, 'Item 22', 8),
       (5, 'Category 5', 23, 'Item 23', 5),
       (5, 'Category 5', 24, 'Item 24', 3),
       (5, 'Category 5', 25, 'Item 25', 4)

SELECT
    *,
    ROW_NUMBER() OVER (PARTITION BY t.CategoryID ORDER BY t.ItemScore DESC) AS RowNumber
FROM 
    Test t

2 个答案:

答案 0 :(得分:0)

您可以尝试将查询写为子查询,然后将RowNumber从request.CRITICAL: Uncaught PHP Exception Aws\Exception\CredentialsException: "Cannot read credentials from /app/.aws/credentials" 1

3

sqlfiddle

答案 1 :(得分:0)

如何?

  • 首先计算CategoryScore(每个类别ItemScore的总和)
  • 然后,根据类别和项目的得分添加“评级”
  • 最后,仅返回两个评分均最高为3的那些记录:

将其放在查询中,如下所示:

WITH
  summing AS (
    SELECT CategoryID, CategoryName, ItemID, ItemName, ItemScore
      , SUM(ItemScore) OVER (PARTITION BY CategoryID) AS CategoryScore
    FROM Test
  ),
  rating AS (
    SELECT CategoryID, CategoryName, ItemID, ItemName, ItemScore
      , DENSE_RANK() OVER (ORDER BY CategoryScore DESC, CategoryID) AS GrpNumber
      , ROW_NUMBER() OVER (PARTITION BY CategoryID ORDER BY ItemScore DESC) AS RowNumber
    FROM summing
  )
SELECT CategoryID, CategoryName, ItemID, ItemName, ItemScore, RowNumber
FROM rating
WHERE GrpNumber <= 3
  AND RowNumber <= 3
ORDER BY GrpNumber, RowNumber;