我使用的是sql server 2008 r2。这是我的询问。
SELECT TOP 25 A.*, U.Displayname AS UserName,
SU.Displayname AS SmoothieAuthorName,
S.Name AS SmoothieName, S.Id AS SmoothieId
FROM dbo.Activity AS A
LEFT JOIN dbo.[User] AS U ON A.UserId = U.Id
LEFT JOIN dbo.[User] AS SU ON A.SmoothieAuthorId = SU.Id
LEFT JOIN dbo.Smoothie AS S ON A.SmoothieId = S.Id
WHERE A.UserId = 2 --@UserId
AND A.UserId <> A.SmoothieAuthorId
ORDER BY CreatedDate DESC
以下是我的结果。现在,我需要通过SmoothieId和CreatedDate对它们进行分组(仅限组日期部分,忽略时间)。前两个应该只返回一个,3到5应该只返回一个。不知道怎么做,请帮忙。
Id ActionType UserId SmoothieId SmoothieAuthorId CreatedDate UserName SmoothieAuthorName SmoothieName SmoothieId
1 view 2 128 1 2013-01-15 20:05:03.403 mike test1234 new testing 2d 128
2 view 2 128 1 2013-01-15 20:16:24.733 mike test1234 new testing 2d 128
12 view 2 128 1 2013-01-16 21:45:56.167 mike test1234 new testing 2d 128
13 view 2 128 1 2013-01-16 22:12:51.217 mike test1234 new testing 2d 128
14 view 2 128 1 2013-01-16 22:12:54.407 mike test1234 new testing 2d 128
15 view 2 69 1 2013-01-16 22:19:54.783 mike test1234 sdfsdfwww 69
答案 0 :(得分:1)
如果你需要来自A的所有列,包括Id,我认为你将很难包括Id。我想你需要明确列出你所追求的A列。 我还假设您想要分组您正在分组的记录,因此需要Count(TheDate)元素。
除此之外,请查看日期时间和组的getting just the date portion。
喜欢的东西;
SELECT ActionType, UserId, SmoothieId, SmoothieAuthorId,
TheDate, Count(TheDate) AS Occurances, UserName, SmoothieAuthorName,
SmoothieName, SmoothieId
FROM (
SELECT TOP 25 A.ActionType, A.UserId, A.SmoothieId,
A.SmoothieAuthorId,
DATEADD(dd, 0, DATEDIFF(dd, 0, CreatedDate)) AS TheDate,
U.Displayname AS UserName,
SU.Displayname AS SmoothieAuthorName,
S.Name AS SmoothieName, S.Id AS SmoothieId
FROM dbo.Activity AS A
LEFT JOIN dbo.[User] AS U ON A.UserId = U.Id
LEFT JOIN dbo.[User] AS SU ON A.SmoothieAuthorId = SU.Id
LEFT JOIN dbo.Smoothie AS S ON A.SmoothieId = S.Id
WHERE A.UserId = 2 --@UserId
AND A.UserId <> A.SmoothieAuthorId
-- ORDER BY CreatedDate DESC
) x GROUP BY ActionType, UserId, SmoothieId, SmoothieAuthorId, UserName,
TheDate, SmoothieAuthorName, SmoothieName, SmoothieId
ORDER BY The Date DESC
注意这未经过测试,只是我尝试的一个快速建议。
答案 1 :(得分:0)
我不确定我完全理解这个问题。假设您需要这些列的不同值,那么只需使用DISTINCT
:
SELECT DISTINCT
CAST(CreatedDate to Date) as DateWanted,
SmoothieId
FROM
(
SELECT TOP 25 A.*, U.Displayname AS UserName,
SU.Displayname AS SmoothieAuthorName,
S.Name AS SmoothieName, S.Id AS SmoothieId
FROM dbo.Activity AS A
LEFT JOIN dbo.[User] AS U ON A.UserId = U.Id
LEFT JOIN dbo.[User] AS SU ON A.SmoothieAuthorId = SU.Id
LEFT JOIN dbo.Smoothie AS S ON A.SmoothieId = S.Id
WHERE A.UserId = 2 --@UserId
AND A.UserId <> A.SmoothieAuthorId
) t
审核您的评论,您说您需要活动表格中的所有字段。对于前2个记录,1或2,您希望在Id列中收到什么?其他列中的所有其他值是否相同?要获得单个记录,您需要选择一行而不是另一行,或者使用具有相同信息的列进行分组。
祝你好运。