我有一个最后的问题,无法用我的sql代码进行排序。基本上,我想透视表并以与此不同的格式显示:http://sqlfiddle.com/#!98436/1年9月
我尝试做的是将LOC_ID和LOC_ID_b转换为平面文件。问题是,要让代码按LOC_ID和LOC_ID_b分组工作,却不知道如何绕过它。
我尝试实现的结果如下:
PN AAA q AAA c BBB q BBB c CCC q CCC c
A1 2 1
RRR 1 1
T1 1 1
HHH 3 3
您可以使用条件聚合。如果你有有限数量的已知loc_id,你可以这样编码
Select pn,
max(case when src = 'h' and loc_id = 'AAA' then val else 0 end) as AAA_qty,
max(case when src = 'r' and loc_id = 'AAA' then val else 0 end) as AAA_count,
max(case when src = 'h' and loc_id = 'BBB' then val else 0 end) as BBB_qty,
max(case when src = 'r' and loc_id = 'BBB' then val else 0 end) as BBB_count,
max(case when src = 'h' and loc_id = 'CCC' then val else 0 end) as CCC_qty,
max(case when src = 'r' and loc_id = 'CCC' then val else 0 end) as CCC_count
from (select 'h' as src, pn, loc_id, sum(qty) val from history group by src,pn,loc_id
union
select 'r' as src, pn, loc_id, count(*) val from rota group by src,pn,loc_id
) s
group by pn
order by pn;
如果您不知道或不想在添加或删除loc_id时更改代码,则需要动态sql
set @sql = (
select concat(
'Select pn,',
group_concat(
concat('max(case when src = ' ,char(39),'h',char(39),' and loc_id = ', char(39),loc_id,char(39), ' then val else 0 end) as ' ,
concat(loc_id,'_qty,')
,
'max(case when src = ' ,char(39),'r',char(39),' and loc_id = ', char(39),loc_id,char(39), ' then val else 0 end) as ' ,
concat(loc_id,'_count')
)
)
,' from ('
,
'select ', char(39),'h',char(39),' as src, pn, loc_id, sum(qty) val from history group by src,pn,loc_id'
,
' union '
,
'select ',char(39),'r',char(39),' as src, pn, loc_id, count(*) val from rota group by src,pn,loc_id
) s
group by pn
order by pn;'
)
from
(
select loc_id from history
union
select loc_id from rota
) a
);
prepare sqlstmt from @sql;
execute sqlstmt;
deallocate prepare sqlstmt;
+-----+---------+-----------+---------+-----------+---------+-----------+
| pn | AAA_qty | AAA_count | BBB_qty | BBB_count | CCC_qty | CCC_count |
+-----+---------+-----------+---------+-----------+---------+-----------+
| A1 | 0 | 0 | 2 | 1 | 0 | 0 |
| HHH | 0 | 0 | 0 | 0 | 3 | 0 |
| RRR | 0 | 0 | 0 | 0 | 0 | 1 |
| T1 | 1 | 1 | 0 | 0 | 0 | 0 |
+-----+---------+-----------+---------+-----------+---------+-----------+
4 rows in set (0.00 sec)