2013-12-11 41 views
0

我在PostgreSQL的9.2以下表中的每個ID:有多少「列1」,「列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

+0

期望的結果是不明確與顯示輸入:23266只有一個病假,不是嗎? 23234有一個病假和一個緊急假。 –

+0

@RaphaëlAlthaus,我在最後一張桌上犯了錯誤。 – Aan

回答

1

類似的東西(不明確的,如果你使用的ID或工資)

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

0

這將顯示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;