如何在 T-SQL 中获取以动态日期作为列的报告
如何获取以动态日期作为 T-SQL 列的报告。
我疯狂地寻找这样的一段代码。
希望它能帮助其他人。
如果有人知道更好的解决方案,请发布。
DECLARE @columns VARCHAR(8000)
SELECT @columns = COALESCE(@columns + ',[' + convert(nvarchar(12), data, 103) + ']',
'[' + convert(nvarchar(12), data, 103)+ ']')
FROM Item
GROUP BY data
--print @columns
DECLARE @query VARCHAR(8000)
SET @query = '
;WITH G1 As
(
select id_item, convert(nvarchar(12), data, 103) as data, COUNT(*) as numar
from Item
group by id_item, data
)
SELECT *
FROM G1
PIVOT
(
sum(numar)
FOR [data]
IN (' + @columns + ')
) AS G2
'
print @query
EXECUTE(@query)
How to get a report with dynamic dates as columns in T-SQL.
I was looking for a piece of code like this like crazy.
Hope it will help other people.
If anyone knows any better solution please post.
DECLARE @columns VARCHAR(8000)
SELECT @columns = COALESCE(@columns + ',[' + convert(nvarchar(12), data, 103) + ']',
'[' + convert(nvarchar(12), data, 103)+ ']')
FROM Item
GROUP BY data
--print @columns
DECLARE @query VARCHAR(8000)
SET @query = '
;WITH G1 As
(
select id_item, convert(nvarchar(12), data, 103) as data, COUNT(*) as numar
from Item
group by id_item, data
)
SELECT *
FROM G1
PIVOT
(
sum(numar)
FOR [data]
IN (' + @columns + ')
) AS G2
'
print @query
EXECUTE(@query)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
关于您问题中的示例的一些评论。
使用
QUOTENAME
而不是自己连接方括号。这将正确处理数据中的任何]
字符。您似乎正在混合
nvarchar
和varchar
。将动态 SQL 变量声明为NVARCHAR(MAX)
(如果面向 SQL Server 2000,则为NVARCHAR(4000)
)而不是VARCHAR(8000)
。这意味着您的查询可以正确处理 Unicode 数据,并且在连接动态 SQL 时通常是更安全的做法。(只是添加一个例子来说明为什么我说这更安全)
A couple of comments on the example in your question.
Use
QUOTENAME
rather than concatenating the square brackets yourself. This will deal correctly with any]
characters in the data.You seem to be mixing
nvarchar
andvarchar
. Declare the dynamic SQL variables asNVARCHAR(MAX)
(orNVARCHAR(4000)
if targeting SQL Server 2000) notVARCHAR(8000)
. This will mean that your query works correctly with Unicode data and is a generally more secure practice when concatenating dynamic SQL.(Just to add an example of why I say this is more secure)
这是一个静态版本(来自同事):
Here is a static version (from a coleague):