每个ID包含多少“column1”,“column2”和“total”并按“total”排序

时间:2013-12-11 12:28:31

标签: sql database postgresql

我在PostgreSQL 9.2中有以下表格:

CREATE TABLE leave
(
  "ID" text NOT NULL,
  "Leave class" text NOT NULL,
  "Leave Date" date NOT NULL,
  CONSTRAINT leave_pkey PRIMARY KEY (payroll, "Leave class", "Leave Date")
)

enter image description here

我想知道每个ID有多少“紧急”,“病假”和“总休假”,并按“总休假”(降序)排序。像这样的东西: enter image description here

2 个答案:

答案 0 :(得分:1)

类似的东西(如果您使用ID或Payroll,则不清楚)

select Payroll,
       sum(case when "Leave class" = 'Emergency' then 1 else 0 end) as "emergency leave",
       sum(case when "Leave class" = 'Sick' then 1 else 0 end) as "Sick leave",
       count(*) as "Total"
FROM leave
group by Payroll
order by count(*) desc;

请参阅SqlFiddle

答案 1 :(得分:0)

这也将显示零计数:如果您想从另一个表中获取工资核算值,那么这很重要

有关详情,请参阅http://sqlfiddle.com/#!12/066de/1

SELECT
  base.payroll,
  leaveCounts.Emergency,
  leaveCounts.Sick,
  leaveCounts.Total
FROM
 (SELECT DISTINCT payroll FROM leave) AS base
  LEFT JOIN
 (SELECT
     COUNT(CASE WHEN "Leave class" = 'Emergency' THEN 1 END) AS Emergency, 
     COUNT(CASE WHEN "Leave class" = 'Sick' THEN 1 END) AS Sick,
     COUNT(*) AS Total,
     payroll
  FROM
      leave
  GROUP BY
     payroll
  ) AS leaveCounts
      ON base.payroll = leaveCOunts.payroll
ORDER BY
  leaveCOunts.Total DESC;

更简单的代码在http://sqlfiddle.com/#!12/066de/3

SELECT
     payroll,
     COUNT(CASE WHEN "Leave class" = 'Emergency' THEN 1 END) AS Emergency, 
     COUNT(CASE WHEN "Leave class" = 'Sick' THEN 1 END) AS Sick,
     COUNT(*) AS Total
  FROM
      leave
  GROUP BY
      payroll
   ORDER BY
     COUNT(*) DESC;