我有一个存储周项的数据库表。
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
问题:使用最大条目数可以很好,但它不会拉回一行或两个条目。
我是否可以使用不同类型的联接来回退一行只有一个或两个条目或以不同的方式接近它?
答案 0 :(得分:2)
这些条目未返回,因为当联接表返回WHERE
值时,NULL
子句显式过滤掉它们。
此解决方案为每条记录添加一个连续的rownumber,每周重新启动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
答案 1 :(得分:1)
您需要在where子句中添加w2.Id is null
或w3.id is null
类似
WHERE
(w2.Id is null and w3.id is null) or
(w3.id is null and w1.id < w2.id) or
(w1.id < w2.id and w2.id < w3.id)
答案 2 :(得分:1)
您也可以使用PIVOT
;WITH CTE AS
(
SELECT Value,
WeekId,
ROW_NUMBER() OVER (PARTITION BY WeekId ORDER BY Id) AS RN
FROM [List].[dbo].[testWeekEntries]
)
SELECT *
FROM CTE
PIVOT (MAX(Value) FOR RN IN ([1],[2],[3]) ) AS PVT