我的数据看起来像这样
MILEAGE January February ........December
0 0 0
2 0.066 0.052
3 0.081 0
5 0 0.062
6 0.080 0 .........
813 0 0 and so on
我希望数据看起来像这样
Mileage January February ..... December
0 (Total of Mileage less and equal to zero for each month)
2000 Total of Mileage upto 2000 for each month
4000 Total of Mileage upto 4000 for each month
6000 Total of Mileage upto 6000 for each month
8000 and so on....
10000
12000
14000
2 thousand increment up till
50000
非常感谢你的帮助。我正在使用SQL Server 2008 R2而不确定如何实现此
答案 0 :(得分:1)
如下所示,您可以使用递归CTE来生成列出动态值的表格。但是,如果它偶尔是一个临时的事情,你只想这样做。如果你打算经常这样做(比如说每个月),就像制作任何其他表一样制作表格,然后你可以添加一个索引并加入它。
最常见的方法是使计数表0,1,2,3等达到一些大数。然后,您可以使用
SELECT val*2000 FROM counting_table WHERE val*2000 >= 5000
获得结果。这个计数表可以用于许多类似的情况但是是通用的。
WITH mile_table as
(
-- use recursive cte to make a table with number 0 - 50000 by 2000
SELECT 0 as milage
UNION ALL
SELECT mile_table.milage+2000
FROM mile_table
WHERE mile_table.milage+2000 <= 50000
)
SELECT mile_table.milage,
sum(a.January) as January,
sum(a.February) as February,
--- ....
sum(a.December) as December,
FROM mile_table
JOIN your_table a ON a.milage >= mile_table.milage
GROUP BY mile_Table.milage
答案 1 :(得分:0)
尝试这样的事情:
DECLARE @i as INT = -2000
CREATE TABLE #T
(
MileageFrom INT,
MileageTo INT
)
WHILE (@i <=50000)
BEGIN
INSERT INTO #T
values(@i, @i+2000)
SET @i= @i+2000
END
SELECT
A.MileageTo,
SUM(January) as january,
SUM(Feburary) as Feb ....,
SUM(DEC) as DEC
FROM YourTable A
JOIN #T B ON A.Mileage BETWEEN B.MileageFrom and B.MileageTo
您需要稍微调整前程万里(MileageFrom)值以包含小于-2000的所有值