我在数据库中有一个表格,显示组织的支出
Office Year Quarter Computer Keyboard Monitor Total
Office1 2014 Q1 1000 300 400 1700
Office1 2014 Q2 400 100 0 500
Office1 2014 Q3 500 0 300 800
Office2 2014 Q1 1500 250 250 2000
Office2 2014 Q2 400 250 250 900
Office2 2014 Q3 1000 100 100 1200
我希望表格像
office Year Usage Q1 Q2 Q3
Office1 2014 Computer 1000 400 500
Office1 2014 Keyboard 300 100 0
Office1 2014 Monitor 400 0 300
Office1 2014 Total 1700 500 800
Office2 2014 Computer 1500 400 1000
Office2 2014 Keyboard 250 250 100
Office2 2014 Monitor 250 250 100
Office2 2014 Total 2000 900 1200
我尝试过以下代码但仅显示office 1的用法
SELECT usage,
MAX(CASE WHEN quarter = 'q1' THEN value END) Q1,
MAX(CASE WHEN quarter = 'q2' THEN value END) Q2,
MAX(CASE WHEN quarter = 'q3' THEN value END) Q3
FROM
(
SELECT quarter, usage,
CASE usage
WHEN 'computer' THEN COMPUTER
WHEN 'keyboard' THEN KEYBOARD
WHEN 'monitor' THEN MONITOR
WHEN 'total' THEN TOTAL
END value
FROM OfficeUsageTable t CROSS JOIN
(
SELECT 'Computer' usage UNION ALL
SELECT 'Keyboard' UNION ALL
SELECT 'Monitor' UNION ALL
SELECT 'Total'
) c
) q
GROUP BY usage;
显示的表格仅适用于office1 ie
office Year Usage Q1 Q2 Q3
Office1 2014 Computer 1000 400 500
Office1 2014 Keyboard 300 100 0
Office1 2014 Monitor 400 0 300
Office1 2014 Total 1700 500 800
我希望显示两个办公室的所有数据。 请协助。
答案 0 :(得分:0)
USAGE
是MySQL reserved word。因此,建议不要在(子)查询中使用列/别名。相反,在这个答案中,子查询中使用了'usg'
。
您的查询中需要进行少量更改,如下所示:
更改1 :您需要在主要表office
中加入year
和OfficeUsageTable
。
更改2 :您需要按office
和usg
字段进行分组。
尝试以下方法:
SELECT office as 'Office', year as 'Year', usg as 'Usage',
MAX(CASE WHEN quarter = 'q1' THEN value END) Q1,
MAX(CASE WHEN quarter = 'q2' THEN value END) Q2,
MAX(CASE WHEN quarter = 'q3' THEN value END) Q3
FROM
(
SELECT office, year, quarter, usg,
CASE usg
WHEN 'computer' THEN COMPUTER
WHEN 'keyboard' THEN KEYBOARD
WHEN 'monitor' THEN MONITOR
WHEN 'total' THEN TOTAL
END value
FROM OfficeUsageTable t CROSS JOIN
(
SELECT 'Computer' as usg UNION ALL
SELECT 'Keyboard' UNION ALL
SELECT 'Monitor' UNION ALL
SELECT 'Total'
) c
) q
GROUP BY office, usg