我正在查询我们车队中的每辆卡车,查看一个月,一个季度或一年的时间内使用的里程数和燃油量。所以我的专栏是Date,Truck,Miles。格式化结果非常耗时,因为所有卡车的数据都如下所示列在一起。
Date Truck Miles
1/1/15 101 542
1/2/15 101 342
有没有办法在复制到Excel或在Excel中将查询作为宏运行时格式化查询结果,以便结果显示为如下所示的3d表?
Truck 1/1/15 1/2/15 1/3/15
101 542 342 741
102 121 214 141
103 541 741 874
答案 0 :(得分:-2)
您必须创建一个存储过程和游标,如下例所示。
SET NOCOUNT ON
DECLARE @au_id varchar(11),
@au_fname varchar(20),
@au_lname varchar(40),
@message varchar(80),
@title varchar(80)
PRINT('-------- Utah Authors report --------')
DECLARE authors_cursor CURSOR FOR
(SELECT au_id, au_fname, au_lname
FROM authors
WHERE state = 'UT'
ORDER BY au_id)
OPEN authors_cursor
FETCH FIRST FROM authors_cursor INTO @au_id, @au_fname, @au_lname
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT(' ')
SET @message = '----- Books by Author: ' + @au_fname + ' ' + @au_lname
PRINT(@message)
-- Declare an inner cursor based
-- on au_id from the outer cursor.
DECLARE titles_cursor CURSOR FOR
(SELECT t.title
FROM titleauthor ta, titles t
WHERE ta.title_id = t.title_id AND
ta.au_id = @au_id) -- Variable value from the outer cursor
OPEN titles_cursor
FETCH FIRST FROM titles_cursor INTO @title
IF @@FETCH_STATUS <> 0
PRINT(' <<No Books>>')
WHILE @@FETCH_STATUS = 0
BEGIN
SET @message = ' ' + @title
PRINT @message
FETCH NEXT FROM titles_cursor INTO @title
END
CLOSE titles_cursor
DEALLOCATE titles_cursor
-- Get the next author.
FETCH NEXT FROM authors_cursor INTO @au_id, @au_fname, @au_lnameEND
CLOSE authors_cursor
DEALLOCATE authors_cursor
GO