0

你好……我想弄清楚如何在 ModelName 列下查看,该列可能包含重复值,并查看同一模型的 ReleaseType 列是否包含“Final Release”。如果是,则不执行任何操作,否则返回唯一模型名称(可能基于最新日期)。绿色字段是我要显示的字段,红色字段不可见: 在此处输入图像描述

这是否可以在 SQL Server 2019 中完成?这是我的表:

CREATE TABLE [dbo].[Model](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [ModelName] [nvarchar](50) NOT NULL,
    [FormFactorID] [int] NOT NULL,
    [Revision] [nvarchar](4) NOT NULL,
    [SVID] [nvarchar](4) NOT NULL,
    [SSID] [nvarchar](4) NULL,
    [Picture] [varbinary](max) NULL,
    [NVME] [nvarchar](4) NULL,
    [ReleaseStatusID] [int] NULL,
 CONSTRAINT [PK__Model__3214EC27B0574C2B] PRIMARY KEY CLUSTERED



CREATE TABLE [dbo].[ReleaseType](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [ReleaseType] [nvarchar](15) NULL,
 CONSTRAINT [PK__ReleaseT__3214EC27CD0730DB] PRIMARY KEY CLUSTERED



CREATE TABLE [dbo].[ProductRelease](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [ReleaseTypeID] [int] NULL,
    [ModelID] [int] NULL,
    [Date] [date] NULL,
    [ECO] [nvarchar](10) NULL,
    [Notes] [nvarchar](800) NULL,
 CONSTRAINT [PK__ProductR__3214EC27CE911F54] PRIMARY KEY CLUSTERED 

ReleaseType 表中的 ID 与 ProductRelease 表中的 ReleaseTypeID 连接

Model 表中的 ID 与 ProductRelease 表中的 ModelID 连接

到目前为止,这是我的查询:

SELECT
    dbo.Model.ModelName, 
    dbo.ReleaseType.ReleaseType, 
    dbo.ProductRelease.ECO, 
    dbo.ProductRelease.Date

FROM            
    dbo.Model 
        INNER JOIN dbo.ProductRelease ON dbo.Model.ID = dbo.ProductRelease.ModelID 
        INNER JOIN dbo.ReleaseType ON dbo.ProductRelease.ReleaseTypeID = dbo.ReleaseType.ID

ORDER BY 
    dbo.Model.ModelName, 
    dbo.ProductRelease.Date
4

1 回答 1

1

是的,例如可以使用窗口函数:

WITH cte AS (
   SELECT m.ModelName, 
     rt.ReleaseType, 
     pr.ECO, 
     pr.Date,
     cnt = COUNT(CASE WHEN rt.ReleaseType='Final Release' THEN 1 END) 
           OVER(PARTITION BY m.ModelName),
     rn = ROW_NUMBER() OVER(PARTITION BY m.ModelName ORDER BY pr.Date DESC)
   FROM dbo.Model m
   JOIN dbo.ProductRelease pr
     ON m.ID = pr.ModelID 
   JOIN dbo.ReleaseType rt
     ON pr.ReleaseTypeID = rt.ID
)
SELECT ModelName, ReleaseType, ECO, Date
FROM cte
WHERE cnt = 0   -- exclude groups with 'Final Release'
  AND rn = 1    -- get only newest occurence per ModelName
ORDER BY ModelName;
于 2020-03-23T15:39:25.063 回答