简体   繁体   English

sql唯一并加入

[英]sql unique and join

This is a lovely little bit of SQL which I can't write. 这是一个可爱的SQL,我不能写。 :) :)

what I need to do is this; 我需要做的就是这个;

select the latest value from the table (CreatedOn), for each user, for a specific StatID. 从表(CreatedOn)中为每个用户选择特定StatID的最新值。 I need to then join the usertable (ssUSER) and select the u.username and I also need to join the detailstatid from the table. 然后我需要加入usertable(ssUSER)并选择u.username,我还需要从表中加入detailstatid。 Ie I just need the latest result from this table for each user and then do a join on the user and detailstatid. 即我只需要为每个用户提供此表的最新结果,然后对用户和detailstatid进行连接。

SELECT TOP 1000
   [DetailStatUserLogID]
  ,[UserID]
  ,[DetailStatID]
  ,[OverviewID]
  ,[Count]
  ,[StatPercent]
  ,[SpecificDate]
  ,[CreatedOn]
  ,[ModifiedOn]
  ,[Note]
  ,[LoggedDate]
  ,[OverViewGUID]
FROM [StartStop].[dbo].[DetailStatUserLog]

SELECT TOP 1000
   [DetailStatID]
  ,[DetailStatGUID]
  ,[NameOfStat]
  ,[DetailOfStat]
  ,[CreatedByType]
  ,[DataType]
  ,[CreatedByGUID]
  ,[CreatedBy]
  ,[ModifiedOn]
  ,[CreatedOn]
  ,[OverviewID]
FROM [StartStop].[dbo].[DetailStat]

SELECT TOP 1000
   [UserID]
  ,[EmailAddress]
  ,[Authenticated]
  ,[UserName]
FROM [StartStop].[dbo].[ssUsers]

Thanks for any help you might be able to give. 感谢您提供的任何帮助。 :) :)

Try: 尝试:

select /* entered desired fields here */
from (select l.*, 
             row_number() over (partition by [UserID], [DetailStatID]
                                order by [CreatedOn] desc) rn
      from DetailStatUserLog l) ll
join ssUsers u on ll.[UserId] = u.[UserId]
Join DetailStat s on ll.[DetailStatId] = s.[DetailStatId]
where ll.rn=1

I think this should do want you want. 我想这应该是你想要的。 It is hard to test without your DDL or data. 没有您的DDL或数据很难测试。

Select u.UserName,
       ds.DetailedStat,
       dsl.CreatedOn,
       dsl.DetailStatId,
       dsl.UserId

From 
(
Select d.UserId, d.DetailStatId, Max(d.CreatedOn) as [CreatedOn]
From DetailStatUserLog d
Where d.CreatedOn = (Select Max(CreatedON)
                   From DetailStatUserLog
                   Where UserID = d.UserId
                   And DetailStatId = d.DetailStatId
                   )
Group By d.UserId, d.DetailStatId

)dsl
Join ssUsers u on dsl.UserId = u.UserId
Join detailstat ds on dsl.DetailStatId = ds.DetailStatId

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM