1

我是 SQL 新手,所以请耐心等待。我正在从多个表中返回数据。下面是我的 SQL(如果有更好的方法,请告诉我):

SELECT [NonScrumStory].[IncidentNumber], [NonScrumStory].[Description], [DailyTaskHours].[ActivityDate], [Application].[AppName], [SupportCatagory].[Catagory], [DailyTaskHours].[PK_DailyTaskHours],n [NonScrumStory].[PK_NonScrumStory] 
FROM [NonScrumStory], [DailyTaskHours], [Application], [SupportCatagory] 
WHERE ([NonScrumStory].[UserId] = 26) 
AND ([NonScrumStory].[PK_NonScrumStory] = [DailyTaskHours].[NonScrumStoryId]) 
AND ([NonScrumStory].[CatagoryId] = [SupportCatagory].[PK_SupportCatagory]) 
AND ([NonScrumStory].[ApplicationId] = [Application].[PK_Application]) 
AND ([NonScrumStory].[Deleted] != 1) 
AND [DailyTaskHours].[ActivityDate] >= '1/1/1990' 
ORDER BY [DailyTaskHours].[ActivityDate] DESC

这是返回的内容:

在此处输入图像描述

这几乎是正确的。我只希望它返回 PK_NonScrumStory 的一份副本,但我不知道如何。本质上,我只希望它返回一份副本,因此不会返回前两行之一。

4

3 回答 3

1

从屏幕截图看来, DISTINCT 应​​该已经解决了您的问题,但如果没有,您可以使用 ROW_NUMBER 函数。

;WITH CTE AS
(
SELECT ROW_NUMBER() OVER (PARTITION BY [NonScrumStory].[PK_NonScrumStory] ORDER BY [DailyTaskHours].[ActivityDate] DESC) AS RowNum,
[NonScrumStory].[IncidentNumber], [NonScrumStory].[Description], [DailyTaskHours].[ActivityDate], [Application].[AppName], [SupportCatagory].[Catagory], [DailyTaskHours].[PK_DailyTaskHours],n [NonScrumStory].[PK_NonScrumStory] 
FROM [NonScrumStory], [DailyTaskHours], [Application], [SupportCatagory] 
WHERE ([NonScrumStory].[UserId] = 26) 
AND ([NonScrumStory].[PK_NonScrumStory] = [DailyTaskHours].[NonScrumStoryId]) 
AND ([NonScrumStory].[CatagoryId] = [SupportCatagory].[PK_SupportCatagory]) 
AND ([NonScrumStory].[ApplicationId] = [Application].[PK_Application]) 
AND ([NonScrumStory].[Deleted] != 1) 
AND [DailyTaskHours].[ActivityDate] >= '1/1/1990' 
)
SELECT * FROM CTE WHERE RowNum = 1 ORDER BY [ActivityDate] DESC
于 2013-07-09T14:28:14.923 回答
1

您可以按 NonScrumStore 列分组,然后像这样聚合其他列:

SELECT [NonScrumStory].[IncidentNumber], 
       [NonScrumStory].[Description], 
       MAX( [DailyTaskHours].[ActivityDate]), 
       MAX( [Application].[AppName]), 
       MAX([SupportCatagory].[Catagory]), 
       MAX([DailyTaskHours].[PK_DailyTaskHours]), 
       [NonScrumStory].[PK_NonScrumStory] 
FROM [NonScrumStory], 
     [DailyTaskHours], 
     [Application], 
     [SupportCatagory] 
WHERE ([NonScrumStory].[UserId] = 26) 
AND ([NonScrumStory].[PK_NonScrumStory] = [DailyTaskHours].[NonScrumStoryId]) 
AND ([NonScrumStory].[CatagoryId] = [SupportCatagory].[PK_SupportCatagory]) 
AND ([NonScrumStory].[ApplicationId] = [Application].[PK_Application]) 
AND ([NonScrumStory].[Deleted] != 1) 
AND [DailyTaskHours].[ActivityDate] >= '1/1/1990'
group by [NonScrumStory].[IncidentNumber], [NonScrumStory].[Description],[NonScrumStory].[PK_NonScrumStory]   
ORDER BY 3 DESC
于 2013-07-09T14:12:01.813 回答
0

我相信如果您将 DISTINCT 添加到您的查询中应该可以解决您的问题。像这样

SELECT DISTINCT [NonScrumStory].[IncidentNumber], [NonScrumStory].[Description],...

于 2013-07-09T14:12:29.523 回答