我有一个存储周条目的数据库表。
Id Value WeekId 1 1.0000 1 2 2.0000 1
同一星期最多可以有三个条目。
所以我想使用自我连接可以解决这个问题
SELECT w1.Value, w2.Value, w3.Value FROM [List].[dbo].[testWeekEntries] as w1 LEFT OUTER JOIN [List].[dbo].[testWeekEntries] as w2 ON w1.WeekId = w2.weekId LEFT OUTER JOIN [List].[dbo].[testWeekEntries] as w3 ON w2.WeekId = w3.WeekId WHERE w1.Id < w2.Id AND w2.Id < w3.Id
问题:使用最大条目数时,它会很糟糕,但是不会回退包含一个或两个条目的行。
我是否可以使用其他类型的联接来拉回仅包含一个或两个条目的行,或者采用不同的方式来实现这一点?
这些条目不会返回,因为您的WHERE子句会在联接表返回NULL值时显式过滤掉它们。
WHERE
NULL
此解决方案将连续的行号添加到每条记录,然后每周重新启动为1。这使您可以在PIVOT语句中使用此序列号
SQL 2000陈述式
SELECT * FROM ( SELECT (SELECT COUNT(*) FROM testWeekEntries WHERE Id <= we.Id AND WeekId = we.WeekId) as rn , Value , WeekId FROM testWeekEntries we ) q PIVOT (MAX(Value) FOR rn IN ([1],[2],[3]) ) AS PVT
SQL 2008语句
;WITH q AS ( SELECT rn = ROW_NUMBER() OVER (PARTITION BY WeekId ORDER BY Id) , Id , Value , WeekId FROM [testWeekEntries] as w1 ) SELECT Value , (SELECT Value FROM q q1 WHERE q1.rn = q.rn + 1 AND q1.WeekId = q.WeekId) , (SELECT Value FROM q q2 WHERE q2.rn = q.rn + 2 AND q2.WeekId = q.WeekId) FROM q WHERE q.rn = 1