|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
我从示例数据库(Oracle)查询获得了一个表格,我可以通过静态的方式用pivot去将行转换为列,请问怎么能实现动态转换呢?我的这个代码示例,仅仅能实现静态的转换,因为没有选择固定字段,所以用处不大,但是当固定字段减少的时候,用处就能体现出来。
我现在遇到的问题有一下几点,希望有大神能够帮忙一下,不胜感激。
1. 第一行的 * 的字段名称,分为固定字段和动态字段,我希望能通过变量实现,但是现在遇到一个问题,就是当字符串为'Accounting' AS "Accounting" 这样的时候,怎么使用转义字符,因为在IN 函数里面,'Accounting’是对的,但是Accounting就不行,如果不加AS “Accounting”呢,又会遇到字段名称里面有单引号。
2. 如何实现一个这样的赋值:
a. dynamic_col:= SELECT DISTINCT td.department_name FROM departments td;
b. fixed_col:='regions','country','city';
3. 我看见网上有一些关于动态行列转换的讲解,比如PIVOT XML....,还有一些使用过程的,遗憾还是没能成功。光赋值就把我难住了。
附件“动态行转列” 是我已经查询出来之后的表格
附件“HR” 则是所有可能在查询中会涉及到的表格
SELECT * FROM (
SELECT te.employee_id AS eid,
CONCAT(te.first_name,CONCAT(' ',te.last_name)) AS fullname,
te.email,
td.department_name AS dept,
te.job_id,
tj.job_title,
tj.min_salary,
tj.max_salary,
tr.region_name AS regions,
tl.country_id,
tc.country_name AS country,
tl.city,
te.hire_date,te.salary,
(CASE WHEN salary< tj.min_salary THEN 'Low'
WHEN salary>tj.max_salary THEN 'High'
ELSE 'Normal' END) AS salevaluation
FROM employees te
LEFT JOIN departments td ON te.department_id=td.department_id
LEFT JOIN jobs tj ON te.job_id=tj.job_id
LEFT JOIN locations tl ON td.location_id=tl.location_id
LEFT JOIN countries tc ON tl.country_id=tc.country_id
LEFT JOIN regions tr ON tc.region_id=tr.region_id
WHERE te.employee_id IS NOT NULL)
PIVOT (AVG(salary) FOR dept IN ('Accounting' AS "Accounting",'Administration' AS "Administration",
'Benefits' AS "Benefits",'Construction' AS "Construction",'Contracting' AS "Contracting",
'Control And Credit' AS "Control And Credit",'Corporate Tax' AS "Corporate Tax",'Executive' AS "Executive",
'Finance' AS "Finance",'Government Sales' AS "Government Sales",'Human Resources' AS "Human Resources",
'IT' AS "IT",'IT Helpdesk' AS "IT Helpdesk",'IT Support' AS "IT Support",'Manufacturing' AS "Manufacturing",
'Marketing' AS "Marketing",'NOC' AS "NOC",'Operations' AS "Operations",'Payroll' AS "Payroll",
'Public Relations' AS "Public Relations",'Purchasing' AS "Purchasing",'Recruiting' AS "Recruiting",
'Retail Sales' AS "Retail Sales",'Sales' AS "Sales",'Shareholder Services' AS "Shareholder Services",
'Shipping' AS "Shipping",'Treasury' AS "Treasury"))
ORDER by eid;
|
|