Sql使用按功能分组

时间:2013-03-12 10:54:03

标签: sql

这是我的数据表。我需要获取每个Employee BasicSalaryCodeTravelPhoneESI.PF

任何人都可以帮忙吗?

year | month | EmpID | Component | Amount | Remarks
2013 | 3     | 2     | Basicsal  | 15000  | dsf
2013 | 3     | 2     | CODE      | 2      | dsf
2013 | 3     | 2     | Travel    | 0      | dsf
2013 | 3     | 2     | Phone     | 1500   | dsf
2013 | 3     | 2     | Internet  | 500    | dsf
2013 | 3     | 2     | Bus Allo  | 0      | dsf
2013 | 3     | 2     | BF        | 0      | dsf
2013 | 3     | 2     | ESI       | 0      | dsf
2013 | 3     | 2     | Medic     | -500   | dsf
2013 | 3     | 2     | Cress     | 101752 | af
2013 | 3     | 2     | Net       | 101552 | asf
etc. | ..    | ..    | ...       | ....   | ...

但我需要这样的输出

Year | Month | EmpID | Basicsalary | CODE | Travel | Phone | cress  | net 
2013 | 3     | 2     | 15000       | 2    | 0      | 1500  | 101752 | 101552

2 个答案:

答案 0 :(得分:1)

由于您没有指定您正在使用的RDBMS,请尝试以下操作:

SELECT 
  year,
  month,
  EmpID,
  MAX(CASE WHEN Component = 'Basicsalary' THEN Amount END) AS Basicsalary,
  MAX(CASE WHEN Component = 'Code'        THEN Amount END) AS Code,
  MAX(CASE WHEN Component = 'Travel'      THEN Amount END) AS Travel,
  MAX(CASE WHEN Component = 'Phone'       THEN Amount END) AS Phone,
  MAX(CASE WHEN Component = 'Chress'      THEN Amount END) AS Chress,
  MAX(CASE WHEN Component = 'net'         THEN Amount END) AS net,
FROM tablename
GROUP BY year, 
         month,
         EmpId;

答案 1 :(得分:1)

如果您使用SQL Server或Oracle作为数据库,则可以应用PIVOT函数来获取结果。

您的代码将类似于以下内容:

select year, 
  month, 
  empid,
  Basicsal, 
  Code, 
  Travel, 
  Phone, 
  Cress, 
  Net
from
(
  select year, month, empid, component, amount
  from yourtable
) src
pivot
(
  max(amount)
  for component in (Basicsal, Code, Travel, Phone, Cress, Net)
) piv