如何分组并选择1行,或者如果只有最后一行使用SQL SELECT,则可以选择1行

时间:2016-02-21 19:22:07

标签: sql-server

我有一个在SQL Server 2014存储过程中运行的SELECT。

SELECT   AdminTest.Title       AS Title,
         COUNT(AdminTestQuestion.AdminTestQuestionId) AS Q,
         UserTest.UserTestId AS UId,
         UserTest.TestStatusId AS Status,
         UserTest.Sequence As Sequence
FROM     AdminTest 
JOIN     UserTest
ON       AdminTest.AdminTestId = UserTest.AdminTestId 
AND      UserTest.UserId = @UserId
JOIN     AdminTestQuestion
ON       AdminTest.AdminTestId = AdminTestQuestion.AdminTestId
GROUP BY AdminTest.Title, 
         UserTest.TestStatusId, 
         UserTest.UserTestId,
         UserTest.Sequence

以下是上面选择的数据:

Title    Q      UId     Status   Sequence
TestA    25     null    0        1
TestA    25     1235    2        2
TestB    10     null    0        1
TestB    10     1237    2        2
TestB    10     1238    2        3
TestC    10     null    0        1

以下是我想要的数据:

Title    Q      UId     Status   Sequence
TestA    25     1235    2        2 
TestB    10     1237    2        2 
TestB    10     1238    2        3
TestC    10     null    0        1

我坚持的是我需要:

  • 如果测试只有一行,我需要显示该行
  • 如果测试有多行,我需要按照序列号的顺序显示除第一行之外的每一行。

我知道这很令人困惑,我认为只有SELECT才能做到这一点。

我很感激有关这方面的任何建议。如果需要,我可以使用存储过程跟随SELECT并使用CURSOR,但我真的不知道从哪里开始使用CURSORS。

希望有人可以提供建议。

1 个答案:

答案 0 :(得分:1)

根据您的评论,您可以尝试这样做:

查询将使用“Seq”高于1 并且“Seq”为1,但仅当没有更高的“Seq”时才会查询:

;WITH MyQuery AS
(
    SELECT   AdminTest.Title       AS Title,
             COUNT(AdminTestQuestion.AdminTestQuestionId) AS Questions,
             UserTest.UserTestId AS UserTestId,
             UserTest.TestStatusId AS UserTestStatusId,
             UserTest.Sequence As Seq
    FROM     AdminTest 
    JOIN     UserTest
    ON       AdminTest.AdminTestId = UserTest.AdminTestId 
    AND      UserTest.UserId = @UserId
    JOIN     AdminTestQuestion
    ON       AdminTest.AdminTestId = AdminTestQuestion.AdminTestId
    GROUP BY AdminTest.Title, 
             UserTest.TestStatusId, 
             UserTest.UserTestId,
             UserTest.Sequence
)
SELECT *
FROM MyQuery
WHERE Seq>1
   OR (Seq=1 
       AND NOT EXISTS(SELECT 1 
                      FROM MyQuery AS innerQuery 
                      WHERE innerQuery.Title=MyQuery.Title
                        AND innerQuery.Seq>1)
      );