如果有2条记录,如何选择第二条记录,如果有一条,则只选择一条?

时间:2018-12-12 16:51:17

标签: sql sql-server

我有一个查询,可能返回1或2条记录。如果查询返回2,我想选择第二条记录,否则只需选择1。我该怎么办?

2 个答案:

答案 0 :(得分:2)

“第二个”意味着您要考虑排序-因为结果集表示无序集,除非有明确的排序,只需颠倒排序并选择排名靠前的记录即可:

select top (1) q.*
from (<your query here>) q
order by ? desc;

答案 1 :(得分:0)

样本数据和预期结果会有所帮助。当您提供此信息时,它将帮助您确定打算如何选择第二行,即基于什么?

在没有样本数据的情况下,这是一个简单的示例,展示了解决该问题的方法。

USE master;
GO
CREATE DATABASE MixedMartialArts;
GO
USE MixedMartialArts;
GO
CREATE SCHEMA mma;
GO
CREATE TABLE mma.Team (
    Id int IDENTITY (1,1) PRIMARY KEY NOT NULL,
    TeamName nvarchar(100) NOT NULL,
    Country nvarchar(100) NOT NULL,
);
GO
CREATE TABLE mma.Fighter (
    Id int IDENTITY (1,1) PRIMARY KEY NOT NULL,
    TeamId int NOT NULL,
    FighterName nvarchar(100) NOT NULL,
    Country nvarchar(100) NOT NULL,
    Reputation int NOT NULL,
    FOREIGN KEY (TeamId) REFERENCES mma.Team(Id)
);
GO
INSERT INTO mma.Team
    (TeamName,Country)
VALUES
    ('American Kickboxing Academy','USA'),
    ('Nova União','Brazil'),
    ('Straight Blast Gym','Ireland'),
    ('London Shootfighters','England');
GO
INSERT INTO mma.Fighter
    (TeamId, FighterName, Country, Reputation)
VALUES
    (1,'Daniel Cormier','USA',9),
    (1,'Khabib Nurmagomedov','Russia',8),
    (2,'Jose Aldo Jr.','Brazil',8),
    (3,'Conor McGregor','Ireland',9),
    (4,'Kay Em Em','England',10)
;
GO
-- 1. Query that may return 1 or 2 rows.
SELECT              t.TeamName,
                    f.FighterName
FROM                mma.Team t
    INNER JOIN      mma.Fighter f ON t.Id = f.TeamId;
GO

R packages

-- 2. For the query that may return 1 or 2 rows, you want to return the second row if the query returns 2 rows, otherwise just select 1 row.
WITH FighterTeam AS (
    SELECT          t.TeamName,
                    f.FighterName,
                    ROW_NUMBER() OVER (PARTITION BY f.TeamId ORDER BY f.Reputation ASC) AS RowNum
    FROM            mma.Fighter f
        INNER JOIN  mma.Team t ON f.TeamId = t.Id
), FighterTeamGrouping AS (
    SELECT          TeamName,
                    COUNT(RowNum) AS Total
    FROM            FighterTeam
    GROUP BY        TeamName
)
SELECT              ft.TeamName,
                    ft.FighterName
FROM                FighterTeam ft
    INNER JOIN      FighterTeamGrouping ftg ON ft.TeamName = ftg.TeamName
WHERE               ft.RowNum = CASE WHEN ftg.Total = 1 THEN 1 ELSE 2 END;

results of query 1