我正在将MS Access数据库移至MySQL,但是我遇到了一些查询问题。
我已经完成了将查询转移到80%的工作,但是这一特殊问题给我带来了麻烦。
TRANSFORM Nz(Max(IIf([charge_description_code] In ('AHS','AHW','AHL','RES','SAT'),"Y","N")), "N") AS Data
SELECT shipment_details.tracking_number, shipment_details.invoice_number
FROM shipment_details
WHERE tracking_number is not null
and charge_category_detail_code not in ('RADJ')
GROUP BY shipment_details.tracking_number, shipment_details.invoice_number
PIVOT shipment_details.charge_description_code In (SAT,AHW,AHS,AHL,RES);
我希望结果显示如下:
tracking_number invoice_number SAT AHW AHS AHL RES
1Z2XXXXXXXXX625816 1329102975 N N N N N
1Z3YYYYYYYYY610514 1329109647 N N Y N N
1Z3ZZZZZZZZZ142605 1329109647 N N N Y Y
答案 0 :(得分:0)
请考虑条件聚合,该条件聚合仍将在MS Access中起作用(将IF
替换为下面的IIF
)。通常,Access的交叉表查询不仅仅针对少数几个,而且还针对少数几个数据透视表。另外,您的NZ
是多余的,因为NULL
根据条件逻辑解析为N
。
SELECT s.tracking_number,
s.invoice_number,
MAX(IF(s.[charge_description_code] = 'SAT', 'Y', 'N')) AS 'SAT',
MAX(IF(s.[charge_description_code] = 'AHW', 'Y', 'N')) AS 'AHW',
MAX(IF(s.[charge_description_code] = 'AHL', 'Y', 'N')) AS 'AHL',
MAX(IF(s.[charge_description_code] = 'AHS', 'Y', 'N')) AS 'AHS',
MAX(IF(s.[charge_description_code] = 'RES', 'Y', 'N')) AS 'SAT'
FROM shipment_details s
WHERE s.tracking_number IS NOT NULL
AND s.charge_category_detail_code NOT IN ('RADJ')
AND s.charge_description_code IN ('AHS','AHW','AHL','RES','SAT')
GROUP BY s.tracking_number,
s.invoice_number
答案 1 :(得分:0)
我认为transform
返回未设置任何值的行。在这种情况下,适当的转换更像这样:
SELECT s.tracking_number, s.invoice_number,
MAX(CASE WHEN s.charge_description_code = 'SAT' THEN 'Y' ELSE 'N' END) AS SAT,
MAX(CASE WHEN s.charge_description_code = 'AHW' THEN 'Y' ELSE 'N' END) AS AHW,
MAX(CASE WHEN s.charge_description_code = 'AHL' THEN 'Y' ELSE 'N' END) AS AHL,
MAX(CASE WHEN s.charge_description_code = 'AHS' THEN 'Y' ELSE 'N' END) AS AHS,
MAX(CASE WHEN s.charge_description_code = 'RES' THEN 'Y' ELSE 'N' END) AS RES
FROM shipment_details s
WHERE s.tracking_number IS NOT NULL AND
s.charge_category_detail_code NOT IN ('RADJ')
GROUP BY s.tracking_number, s.invoice_number;