一.
在行轉列時,拼結多個問題的答案,放到乙個列中顯示
create function [dbo].[aggregatestring]
( @func_code varchar(20),
@emp_id int,
@store_id int,
@biz_date varchar(20),
@acvt_id int,
@qst_id int ---問題id
) returns varchar(1024)
as begin
declare @str varchar(1024)
select @str = isnull(@str+',','')+val
from v_visit_acvt_for_fac
where qst_id = @qst_id
and func_code =@func_code
and biz_date =@biz_date
and store_id =@store_id
and acvt_id=@acvt_id
and emp_id =@emp_id
return @str
endgo
二.行轉列,關鍵是有乙個固定的id值作為轉運的id,如果沒有這樣的固定id,可以考慮用虛擬的列。生成固定的id值。
with acvt_qstas(
select maq.acvt_id,
maq.qst_id,
mq.qst_name,
row_number() over(partition by maq.acvt_id order by maq.qst_id) rownum
from ms_acvt_qst maq
inner join ms_qst mq
on mq.id = maq.qst_id
where mq.qst_name <> '拍照' --and maq.acvt_id = 18
)select v.emp_id,
v.store_id,
v.biz_date,
v.img_id,
v.func_code,
v.acvt_id,
max(case when qcq.rownum = 1 and
v.qst_id = qcq.qst_id
then qcq.qst_name
else null
end ) as question1,
max(case when qcq.rownum = 1 and
v.qst_id = qcq.qst_id
then dbo.aggregatestring(func_code,emp_id,store_id,biz_date,v.acvt_id,v.qst_id)
else null
end ) as answer1,
max(case when qcq.rownum = 2 and
v.qst_id = qcq.qst_id
then qcq.qst_name
else null
end ) as question2,
max(case when qcq.rownum = 2 and
v.qst_id = qcq.qst_id
then dbo.aggregatestring(func_code,emp_id,store_id,biz_date,v.acvt_id,v.qst_id)
else null
end ) as answer2,
max(case when qcq.rownum = 3 and
v.qst_id = qcq.qst_id
then qcq.qst_name
else null
end ) as question3,
max(case when qcq.rownum = 3 and
v.qst_id = qcq.qst_id
then dbo.aggregatestring(func_code,emp_id,store_id,biz_date,v.acvt_id,v.qst_id)
else null
end ) as answer3,
max(case when qcq.rownum = 4 and
v.qst_id = qcq.qst_id
then qcq.qst_name
else null
end ) as question4,
max(case when qcq.rownum = 4 and
v.qst_id = qcq.qst_id
then dbo.aggregatestring(func_code,emp_id,store_id,biz_date,v.acvt_id,v.qst_id)
else null
end ) as answer4
from v_visit_acvt_temp v
inner join acvt_qst qcq
on qcq.acvt_id = v.acvt_id
where biz_date ='2012-03-01' and func_code ='fac_40'--and store_id =55140
group by v.emp_id,
v.store_id,
v.biz_date,
v.img_id,
v.func_code,
v.acvt_id
Oracle 行轉列 的例子
乙個同事寫的,那出來和大家分享一下 create table score fname nvarchar2 50 fsubject nvarchar2 50 fresult decimal 18,0 insert into score values 張三 語文 20 insert into score...
sql 行轉列問題
題目 下表tproduct某產品在各城市各月銷量情況 city name month no 月 qut qty 臺 杭州 9 100 杭州 10 120 上海 9 130 上海 10 140 請寫sql實現 如下查詢 city 9月銷量 10月銷量 杭州 100 120 上海 130 140 答案一...
SQL 行轉列總結
行轉列應該使用case 想要把某個行轉成列的列名 when 裡將各個列的值放進去 then 分組後某個值要進行彙總行 else 0 end 動態生成的話,將想要用的轉的,用selec查出來拼成以上格式就可以了 declare sql varchar 8000 如果大於8000只能用程式去拼乙個sql...