根据标准寻找独特价值

Find Unique Value based on criteria

你好…我想弄清楚如何在 ModelName 列下查看,该列可能包含重复值,并查看同一型号的 ReleaseType 列是否包含“最终版本”。如果是,则什么也不做,如果不是 Return Unique ModelName(可能基于最新日期)。绿色字段是我要显示的字段,红色字段应该不可见:

这可以在 SQL Server 2019 中完成吗? 这是我的 tables:

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 table 与 ProductRelease 中的 ReleaseTypeID 相结合 table

来自模型 table 的 ID 与来自 ProductRelease table

的模型 ID 合并

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

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

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

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;