答案 0 :(得分:0)
这是一个动态SQL脚本,其中使用带有For XML Path的SQL string concatenation方法动态构建标签和值
请注意,以下脚本缺少条形颜色,这些颜色应作为相同数量的标签动态附加到SQL
因此,可以在存储条形标签颜色的表上执行类似的连接方法。将列表作为单个字符变量提取后,可以将其添加到适当位置的@SQL
--create table reportData (year int, type varchar(10), qty int)
--insert into reportData select 2013, 'Type 1',1
--insert into reportData select 2014, 'Type 1',2
--insert into reportData select 2015, 'Type 3',1
--insert into reportData select 2016, 'Type 2',1
--insert into reportData select 2016, 'Type 3',2
--insert into reportData select 2016, 'Type 4',4
declare @sql nvarchar(max)
declare @labels nvarchar(max)
declare @measures nvarchar(max)
SELECT
@labels =
STUFF(
(
SELECT distinct
',"' + convert(nvarchar(4),[year]) + '"'
FROM reportData
FOR XML PATH('')
), 1, 1, ''
)
SELECT
@measures =
STUFF(
(
SELECT
',' + convert(nvarchar(4),qty)
FROM (
select
years.year, data.qty
from (
select distinct year from reportData
) years
left join (
select sum(qty) as qty, year from reportData group by year
) data on years.year = data.year
) Q
FOR XML PATH('')
), 1, 1, ''
)
set @sql = N'
var data = {
labels: ['+ @labels + '],
datasets: [
{
label: "My Graph",
backgroundColor: [
''rgba(255, 99, 132, 0.2)'',
''rgba(54, 162, 235, 0.2)'',
''rgba(255, 206, 86, 0.2)'',
''rgba(75, 192, 192, 0.2)'',
],
borderColor: [
''rgba(255,99,132,1)'',
''rgba(54, 162, 235, 1)'',
''rgba(255, 206, 86, 1)'',
''rgba(75, 192, 192, 1)'',
],
borderWidth: 1,
data: ['+ @measures +'],
}
]
};'
print @sql