我问了这个问题并得到了一个很好的答案:How to assign date value to all returned mysql queries但现在我需要在MS SQL(SQL Server 2005)中做同样的事情。警告是我有一个案例陈述,似乎是破坏事情。我有两个问题:
select * from (select row_number()
over (order by a.device ASC)
AS rownum, a.device, staff, requestDate, m.maxDate, attribute =
REPLACE((SELECT attribute AS [data()]
FROM deviceList
WHERE device = a.device
ORDER BY device FOR xml PATH('')), ' ', ' ')
FROM deviceList a
INNER JOIN (SELECT device, MAX(requestDate) AS maxDate
FROM ASSIGNMENT GROUP BY device) m on m.device = a.device
RIGHT JOIN Assignment
ON (Assignment.device=a.device)
GROUP BY a.device, staff, maxDate, requestDate, contract)
AS B WHERE B.rownum > 0;
select * from (select row_number()
over (order by a.device ASC)
AS rownum, a.device, staff, requestDate, CONVERT(
varchar, dateadd(year,
(CASE
WHEN contract = '10' THEN 1
WHEN contract = '20' THEN 2
WHEN contract = '30' THEN 3
ELSE 3
END), m.maxDate) 107) as myEndDate, attribute =
REPLACE((SELECT attribute AS [data()]
FROM deviceList
WHERE device = a.device
ORDER BY device FOR xml PATH('')), ' ', ' ')
FROM deviceList a
INNER JOIN (SELECT device, MAX(requestDate) AS maxDate
FROM ASSIGNMENT GROUP BY device) m on m.device = a.device
RIGHT JOIN Assignment
ON (Assignment.device=a.device)
GROUP BY a.device, staff, myEndDate, requestDate, contract)
AS B WHERE B.rownum > 0;
第一个语句非常有用,例如条目(具有相同“设备”标签的条目)具有正确的endDate。但是,当我尝试根据case语句递增日期时,事情就会出错。日期递增但不相同。为什么案件陈述会破坏这种性质?
更新: 如果我有一个设备的两个日期值:
2/1/2010
1/1/2010
合同= 10
查询后各自的日期是:
2/1/2011
2/1/2012
答案 0 :(得分:0)
您必须使用CASE
子句中的整个GROUP BY
语句。 SQL Server不一定在执行SELECT
之前处理GROUP BY
元素,因此不能使用在那里定义的别名。 (Longer explanation here)。
SELECT * FROM (SELECT ROW_NUMBER()
OVER (ORDER BY a.device ASC)
AS rownum, a.device, staff, requestDate, CONVERT(
varchar, dateadd(year,
(CASE
WHEN contract = '10' THEN 1
WHEN contract = '20' THEN 2
WHEN contract = '30' THEN 3
ELSE 3
END), m.maxDate) 107) as myEndDate, attribute =
REPLACE((SELECT attribute AS [data()]
FROM deviceList
WHERE device = a.device
ORDER BY device FOR xml PATH('')), ' ', ' ')
FROM deviceList a
INNER JOIN (SELECT device, MAX(requestDate) AS maxDate
FROM ASSIGNMENT GROUP BY device) m on m.device = a.device
RIGHT JOIN Assignment
ON (Assignment.device=a.device)
GROUP BY a.device, staff, CONVERT(
varchar, dateadd(year,
(CASE
WHEN contract = '10' THEN 1
WHEN contract = '20' THEN 2
WHEN contract = '30' THEN 3
ELSE 3
END), m.maxDate) 107), requestDate, contract)
AS B WHERE B.rownum > 0;