Добавьте " как " в динамическую кросс-таблицу SQL server
Привет ,
Я создаю динамическую перекрестную таблицу
DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX); SET @columns = N''; SELECT @columns += N', p.' + QUOTENAME(doc_select) FROM (select d.doc_select from doc_sup_sch d group by d.doc_select) x ; SET @sql = N' SELECT sch_id,examid,user_name, sch_type,' + STUFF(@columns, 1, 2, '') + ' FROM ( select sch_id,examid,user_name, sch_type, doc_select from adminusers a inner join doc_sup_sch d on a.user_id = d.sch_id where d.examid = 11 and org_id = 40088 ) j PIVOT ( count(doc_select) for doc_select in (' + STUFF(REPLACE(@columns, ', p.[', ',['), 1, 1, '') + ') ) AS p;'; PRINT @sql; EXEC sp_executesql @sql;
результат
SELECT sch_id,examid,user_name, sch_type,p.[جيد], p.[مناسب جدا], p.[غير مناسب], p.[مناسب] FROM ( select sch_id,examid,user_name, sch_type, doc_select from adminusers a inner join doc_sup_sch d on a.user_id = d.sch_id where d.examid = 11 and org_id = 40088 ) j PIVOT ( count(doc_select) for doc_select in ([جيد],[مناسب جدا],[غير مناسب],[مناسب]) ) AS p;
Я хотел бы добавить " как " после поля же это
SELECT sch_id,examid,user_name, sch_type,p.[جيد] as g01, p.[مناسب جدا] as g02, p.[غير مناسب] as g03, p.[مناسب] as g04 FROM ( select sch_id,examid,user_name, sch_type, doc_select from adminusers a inner join doc_sup_sch d on a.user_id = d.sch_id where d.examid = 11 and org_id = 40088 ) j PIVOT ( count(doc_select) for doc_select in ([جيد],[مناسب جدا],[غير مناسب],[مناسب]) ) AS p;
Как мне это сделать?
Большое спасибо
Что я уже пробовал:
DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX); SET @columns = N''; SELECT @columns += N', p.' + QUOTENAME(doc_select) + 'g0' + CONVERT(varchar(10), doc_select_id) FROM (select d.doc_select from doc_sup_sch d group by d.doc_select) x ; SET @sql = N' SELECT sch_id,examid,user_name, sch_type,' + STUFF(@columns, 1, 2, '') + ' FROM ( select sch_id,examid,user_name, sch_type, doc_select from adminusers a inner join doc_sup_sch d on a.user_id = d.sch_id where d.examid = 11 and org_id = 40088 ) j PIVOT ( count(doc_select) for doc_select in (' + STUFF(REPLACE(@columns, ', p.[', ',['), 1, 1, '') + ') ) AS p;';