我已经在sql server中编写了以下存储过程
CREATE PROCEDURE usp_getQuantityBilling()
-- VARIABLE --
DECLARE @cols AS NVARCHAR(MAX)
DECLARE @query AS NVARCHAR(MAX)
select @cols = group_concat(name)
from visit_groups where arm_id='377';
set @query = 'SELECT id, service, rate, subjectcount, armDetailsId, totalHours,'
+ @cols + ' FROM
(
select protocols.id, arms.name, visit_groups.name as visitGroup, services.name as serviceName, visits.quantity,
line_items_visits.subject_count
from protocols,arms,visit_groups,visits,line_items,line_items_visits,services
where protocols.id = arms.protocol_id
and visit_groups.arm_id = arms.id
and visits.visit_group_id = visit_groups.id
and line_items_visits.arm_id = arms.id
and visits.line_items_visit_id = line_items_visits.id
and line_items_visits.line_item_id = line_items.id
and services.id = line_items.service_id
and protocols.id = ''' + 591 + '''
) x
pivot
(
max(isActive)
for visitName in (' + @cols + ')
) p';
execute (@query)
我正在尝试将其转换为mysql服务器,但是我不确定如何在mysql存储的proc中声明变量,以及如何一起运行所有这些查询,以便将上一个查询生成的结果用于下一个查询。
也在下面的查询中:
select @cols = group_concat(name)
from visit_groups where arm_id='377';
出现错误
错误代码:1267。非法的排序规则混合(utf8_general_ci,IMPLICIT) 和(utf8_unicode_ci,IMPLICIT)执行操作'='0.000秒
所以我寻找了解决方案,并像这样
select @cols = group_concat(name) COLLATE utf8_unicode_ci from visit_groups
where arm_id='377';
现在我得到的结果是列名为@cols = group_concat(name) COLLATE utf8_unicode_ci
的0,但是结果实际上应该看起来像visit1,visit 2,因为那是我在sql server中得到的。
修改
SELECT id, name, visitGroup, serviceName, quantity, subject_count,'
+ [Visit 1],[Visit 2] + ' FROM
(
select protocols.id, arms.name, visit_groups.name as visitGroup, services.name as serviceName,
visits.quantity,
line_items_visits.subject_count
from protocols,arms,visit_groups,visits,line_items,line_items_visits,services
where protocols.id = arms.protocol_id
and visit_groups.arm_id = arms.id
and visits.visit_group_id = visit_groups.id
and line_items_visits.arm_id = arms.id
and visits.line_items_visit_id = line_items_visits.id
and line_items_visits.line_item_id = line_items.id
and services.id = line_items.service_id
and protocols.id = ''' + 591 + '''
) x
pivot
(
max(isActive)
for visitName in (' + [Visit 1],[Visit 2] + ')
) p'
主要问题是运行此查询,它显示mysql错误,在错误的位置使用了数据透视,但是在sql中工作正常。无论如何要将这个查询转换成mysql数据透视查询。
注意:此访问1和访问2是动态生成的,但仅为了此解决方案,我手动将其复制到此处。