我有一个工作查询,以提取表中每个距离的每个运动员的最短时间" Tempi"。这是一个简单的逐组查询,通过athleteID和distanceID对结果进行分组,并选择最短时间。但我现在需要知道在何时何地获得这些时间。这些数据位于另一个名为" Manif"的表中。这两个表由ManifID连接,存在于两个表中。如何检索日期和城市的时间? 谢谢!
工作查询
SELECT
[02_tEMPI].CodSpec,
[04_Spec].DescrSpecShort,
Min([02_Tempi].Tempo) AS MinDiTempo
FROM
[04_Spec]
INNER JOIN [03_Manif]
INNER JOIN [02_Tempi]
ON [03_Manif].IDManif = [02_Tempi].CodManif
ON [04_Spec].CodSpec = [02_Tempi].CodSpec
WHERE
[02_Tempi].CodAtleta=@CodAtleta AND
[03_Manif].Base = @Base
GROUP BY
[04_Spec].DescrSpecShort,
[02_Tempi].CodSpec
HAVING
[02_Tempi].CodSpec <'60'
ORDER BY
[02_Tempi].CodSpec
Tempi表结构
CREATE TABLE [dbo].[02_Tempi] (
[IDRisu] BIGINT NOT NULL,
[CodAtleta] VARCHAR (12) NULL,
[CodSpec] VARCHAR (4) NULL,
[CodManif] INT NULL,
[Note] VARCHAR (14) NULL,
[CodSocContingente] VARCHAR (14) NULL,
[Cat] VARCHAR (5) NULL,
[CatFIN] VARCHAR (4) NULL,
[CatPrimato] INT NULL,
[Elaborato] SMALLINT NULL,
[Tempo] VARCHAR (8) NULL,
CONSTRAINT [PK__02_Tempi] PRIMARY KEY CLUSTERED ([IDRisu] ASC)
mANIF表结构
CREATE TABLE [dbo].[03_Manif] (
[IDManif] INT NOT NULL,
[DescrManif] VARCHAR (100) NULL,
[LuogoManif] VARCHAR (50) NULL,
[Base] SMALLINT NULL,
[LinkPDF] VARCHAR (250) NULL,
[Data] VARCHAR (10) NULL,
CONSTRAINT [PK__03_Manif] PRIMARY KEY CLUSTERED ([IDManif] ASC)
);
由于
答案 0 :(得分:2)
我认为你可以做row_number
窗口函数:
;
WITH cte
AS ( SELECT * ,
ROW_NUMBER() OVER ( PARTITION BY [04_Spec].DescrSpecShort,
[02_Tempi].CodSpec ORDER BY [02_Tempi].Tempo ) AS rn
FROM [04_Spec]
INNER JOIN [02_Tempi] ON [04_Spec].CodSpec = [02_Tempi].CodSpec
INNER JOIN [03_Manif] ON [03_Manif].IDManif = [02_Tempi].CodManif
WHERE [02_Tempi].CodAtleta = @CodAtleta
AND [03_Manif].Base = @Base
AND [02_Tempi].CodSpec < '60'
)
SELECT *
FROM cte
WHERE rn = 1
答案 1 :(得分:0)
潜在的方法
使用该ManifID加入Manif表。
SELECT
Min(T1.Tempo) [Fastest Tempo],
T1.AthleteID,
T1.DistanceID,
SUBT.ManifID
FROM [02_Tempi] T1
CROSS APPLY
(
SELECT TOP 1 T2.ManifID
FROM [02_Tempi] T2
WHERE T2.AthleteID = T1.AthleteID
AND T2.DistanceID = T1.DistanceID
ORDER BY T2.Tempo DESC --add other differentiating columns if necessary
) SUBT
JOIN [03_Manif] M
ON SUBT1.ManifID = M.ManifID
GROUP BY
T1.AthleteID,
T1.DistanceID,
SUBT.ManifID