[英]How to get date as Header in SQL Server 2005
I am trying to get dates as headers that change depending on the current date.我试图将日期作为根据当前日期而变化的标题。 Here is an example of what I am trying to do in SQL Server 2005.这是我在 SQL Server 2005 中尝试执行的操作的示例。
select c.[ar cust edi sef type], SUM(case when选择 c.[ar cust edi sef type], SUM(case when
s.[ar sale date] like DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))-7 and s.[ar sale document type] like 'invoice' then s.[AR SALE Balance Due] else 0 end) as getdate(), s.[ar sale date] 像 DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))-7 和 s.[ar sale document type] 像'invoice' then s.[AR SALE Balance Due] else 0 结束) 作为 getdate(),
getdate() does not work. getdate() 不起作用。 Is there a way I can return a date as the header?有没有办法可以将日期作为标题返回?
Column headers can not be dynamic.列标题不能是动态的。 You can see this from the fact that usually you don't specify them as string, but like an identifier.您可以从通常不将它们指定为字符串,而是将它们指定为标识符的事实中看到这一点。
SELECT 1 as TestColumn
instead of代替
SELECT 1 as 'TestColumn'
You could do what you want in the form of a query you execute through exec
您可以以通过exec
执行的查询的形式执行您想要的操作
exec('SELECT 1 AS ' + CONVERT(nvarchar, getdate()))
This code will list the dates as column headers.此代码将日期列为列标题。 Used dynamic PIVOT to obtained the result.使用动态 PIVOT 获得结果。 First I create a table with dates and a random text to test the solution.首先,我创建一个包含日期和随机文本的表格来测试解决方案。 Substitute your table and change the code accordingly.替换您的表并相应地更改代码。
If you can provide your schema and data the answer will be more applicable and practical.如果您可以提供您的架构和数据,答案将更加适用和实用。
DECLARE @StartDate DATE = '20110901'
, @EndDate DATE = '20111001'
SELECT DATEADD(DAY, nbr - 1, @StartDate) AS [Date]
,'test' AS [Value]
into #temp_Dates
FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY c.object_id ) AS Nbr
FROM sys.columns c
) nbrs
WHERE nbr - 1 <= DATEDIFF(DAY, @StartDate, @EndDate)
--------------------------------------------------------------------------------------
-----------Dynamic PIVOT section to make the date as a column header------------------
DECLARE @SQL AS VARCHAR(MAX)
, @cols_ AS vARCHAR(MAX)
, @Table_Name VARCHAR(20)
SET @Table_Name = '#temp_Dates'
--Making the column list dynamically
SELECT @cols_ = STUFF((SELECT DISTINCT ', '+QUOTENAME( [T2].[Date])
FROM #temp_Dates [T2]
FOR XML PATH('')), 1, 1, '')
SET @SQL = ' SELECT
pivoted.*
FROM
(
SELECT *
FROM '+@Table_Name+'
) AS [p]
PIVOT
(
MIN([P].[Value])
FOR [P].[Date] IN (' + @cols_ + ')
) AS pivoted;
';
PRINT( @SQL)
EXEC (@SQL)
DROP TABLE #temp_Dates
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.