日期:2014-05-17  浏览次数:20483 次

SQL难题(高手进)
现有一表数据如下
设备 加油量 加油日期
A1 10 2012-10-1

A2 2 2012-10-2

A3 3 2012-10-1

现在想得到10月份每天每台设备的加油汇总表,如下

日期
设备 1 2 3 4 5 。。。。 31 1-31

A1 10    10 

A2 2 2

A3 3 3

A4 0

日统计 13 2 15



------解决方案--------------------
在精华贴中搜索行列转换
------解决方案--------------------
SQL code

if OBJECT_ID('Business_TB','U') is not null drop table Business_TB
go
--虚拟出一张业务表
with cte as
(    
    select 
        number as 设备,
        number+10 as 加油量,
        DATEADD(DD,number,'2011-10-01') as 加油日期
    from master..spt_values
    where type='p'
    and number between 0 and 30
)
select  * into Business_TB from cte
go
select * from Business_TB
/*
设备          加油量         加油日期
----------- ----------- -----------------------
0           10          2011-10-01 00:00:00.000
1           11          2011-10-02 00:00:00.000
2           12          2011-10-03 00:00:00.000
3           13          2011-10-04 00:00:00.000
4           14          2011-10-05 00:00:00.000
5           15          2011-10-06 00:00:00.000
6           16          2011-10-07 00:00:00.000
7           17          2011-10-08 00:00:00.000
8           18          2011-10-09 00:00:00.000
9           19          2011-10-10 00:00:00.000
10          20          2011-10-11 00:00:00.000
11          21          2011-10-12 00:00:00.000
12          22          2011-10-13 00:00:00.000
13          23          2011-10-14 00:00:00.000
14          24          2011-10-15 00:00:00.000
15          25          2011-10-16 00:00:00.000
16          26          2011-10-17 00:00:00.000
17          27          2011-10-18 00:00:00.000
18          28          2011-10-19 00:00:00.000
19          29          2011-10-20 00:00:00.000
20          30          2011-10-21 00:00:00.000
21          31          2011-10-22 00:00:00.000
22          32          2011-10-23 00:00:00.000
23          33          2011-10-24 00:00:00.000
24          34          2011-10-25 00:00:00.000
25          35          2011-10-26 00:00:00.000
26          36          2011-10-27 00:00:00.000
27          37          2011-10-28 00:00:00.000
28          38          2011-10-29 00:00:00.000
29          39          2011-10-30 00:00:00.000
30          40          2011-10-31 00:00:00.000

(31 row(s) affected)
*/