SQL 查询中的行到列
Posted
技术标签:
【中文标题】SQL 查询中的行到列【英文标题】:ROWS TO COLUMNS IN SQL QUERY 【发布时间】:2020-07-21 13:43:05 【问题描述】:由于我没有明确提出我的最后一个问题,所以我会重新提出我的问题 -
Effective_date Result_value Elementname Person_number
10-JAN-2020 4.6 Taxable Earnings 10
10-JUN-2020 5 Taxable Earnings 10
01-JAN-2020 3.2 Basic Life 10
10-FEB-2020 1.6 Basic Life 10
11-JAN-2020 2.2 Tax Units 10
11-JUL-2020 1.2 Tax Units 10
我有以下查询 -
SELECT ppa.effective_date,
pra.result_value ,
pra.elementname,
prd.person_number
FROM pay_pay_relationships_dn prd
INNER JOIN pay_payroll_rel_actions pra
ON prd.payroll_relationship_id = pra.payroll_relationship_id
INNER JOIN pay_payroll_actions ppa
ON pra.payroll_action_id = ppa.payroll_action_id
INNER JOIN pay_all_payrolls_f pap
ON ppa.element_type_id = pap.element_type_id
WHERE ( and pra.elementname = 'Taxable Earnings'
AND ppa.payroll_id = pap.payroll_id )
This query will give a resultant as -
effective_date result_value elementname person_number
10-JAN-2020 4.6 Taxable Earnings 10
10-JUN-2020 5 Taxable Earnings 10
----------------------------------------------------------------------------------------------------------------------------------
如果有效日期介于我通过的 start_date 和 end_date 之间,我希望输出类似于 result_value 的总和。所以最后的查询
I am using is this to get the desired output-
SELECT SUM(result_value) taxable_earn,
person_number
FROM (
SELECT ppa.effective_date,
pra.result_value ,
pra.elementname,
prd.person_number
FROM pay_pay_relationships_dn prd
inner join pay_payroll_rel_actions pra
ON prd.payroll_relationship_id = pra.payroll_relationship_id
inner join pay_payroll_actions ppa
ON pra.payroll_action_id = ppa.payroll_action_id
inner join pay_all_payrolls_f pap
ON ppa.element_type_id = pap.element_type_id
WHERE (
and pra.elementname = 'Taxable Earnings'
AND ppa.payroll_id = pap.payroll_id )
AND ppa.effective_date BETWEEN :p_start_date AND :p_end_date )
GROUP BY person_number
person_number taxable_earn
10 9.6
我希望输出包含元素名称 result_value ——“基本生活”、“税收单位”在上述输出中的单独列中出现——
person_number taxable_earn Basic_Life Tax_Units
10 9.6 4.8 3.4
如何调整查询以获得如上所示的输出?
【问题讨论】:
【参考方案1】:您可以尝试使用枢轴进行以下查询 -
SELECT *
FROM (SELECT ppa.effective_date,
pra.result_value ,
pra.elementname,
prd.person_number
FROM pay_pay_relationships_dn prd
INNER JOIN pay_payroll_rel_actions pra ON prd.payroll_relationship_id = pra.payroll_relationship_id
INNER JOIN pay_payroll_actions ppa ON pra.payroll_action_id = ppa.payroll_action_id
INNER JOIN pay_all_payrolls_f pap ON ppa.element_type_id = pap.element_type_id
WHERE ppa.payroll_id = pap.payroll_id
AND ppa.effective_date BETWEEN :p_start_date AND :p_end_date)
PIVOT (SUM(result_value )
FOR elementname IN ('taxable_earn' taxable_earn, 'Basic_Life' Basic_Life, 'Tax_Units' Tax_Units))
【讨论】:
这并不完全奏效。自从我提出这个问题以来已经有很多天了,我对我的问题提出了一个单独的问题以上是关于SQL 查询中的行到列的主要内容,如果未能解决你的问题,请参考以下文章