2013-01-24 133 views
1

對不清楚的問題,我的英語不是那麼好。所以,那裏有我的查詢:MySQL計數與組通過

SELECT ticketID, 
status, 
COUNT(status) as count, 
statusName, 
assign 
FROM ticket, department, status 
WHERE ticket.department = 100 
AND ticket.department = department.departID 
AND ticket.status = status.statusID 
GROUP BY statusName,assign 

,這是結果:

| ticketID | count  | statusName | assign | 
|:----------|-----------:|:---------:|:-------: 
| 1002  |   2 |  open | NULL | 
| 1020  |   1 |  open | James | 
| 1021  |   1 |  open | Nick | 
| 1015  |   1 | overdue | NULL | 

我的目標是通過自己的地位來算票,如果狀態=「開放」和分配= null,則狀態會更改爲'未分配',我需要一個更好的解決方案或只是一種方法來合併結果'詹姆斯'和'尼克'是一個,因爲我只需要知道票是否分配。

回答

1

不要看到你需要部門表,認爲你可以安全地將其刪除,但是......

SELECT a.statusID, a.Status, Count(*) 
FROM(
    SELECT statusID, 
    (CASE WHEN statusName = 'open' and assign IS NULL THEN 'unassigned' 
     WHEN statusName ='open' and assign IS NOT NULL THEN 'assigned' 
     ELSE statusName 
     END) as Status 
    FROM ticket 
    INNER JOIN department ON ticket.department = department.departID 
    INNER JOIN status ON ticket.status = status.statusID 
    WHERE ticket.department = 100) as a 
GROUP BY a.Status, a.statusID 

SqlFiddle(簡體)

+0

非常好!你能改進它,以便它可以顯示其他狀態嗎?即狀態關閉計數= 0 – user1918956

+0

哦,我也需要ticketID。 – user1918956

+0

@ user1918956好了,使用ticketID編輯(假設一個ticketID可以出現在很多行中)。但我不確定這會不會給你想要的東西。對於其他狀態(statusName),它們應該已經顯示(例如,在您的示例中過期)。但如果他們不這樣做,你能否給出一個「更大」的樣本? –

0
SELECT ticketID,status,sum(CASE status 
    WHEN 'open' then 1 
    WHEN '' then 1 
    WHEN NULL then 1 
    else 0) as count,statusName,assign 
     FROM ticket, department, status WHERE ticket.department = 100 
     AND ticket.department = department.departID 
     AND ticket.status = status.statusID 
     GROUP BY statusName,assign 
+0

我想你錯過了這個',那麼狀態會改變爲'未分配'' –

+0

我在想,OP是指如何計算事情,而不是實際的狀態更新更新,也許我錯了。 –

1
SELECT ticketID, 
status, 
COUNT(status) as count, 
statusName, 
'unassigned' 
FROM ticket, department, status 
WHERE ticket.department = 100 
AND ticket.department = department.departID 
AND ticket.status = status.statusID 
AND assign is NULL 
GROUP BY statusName 
UNION 
SELECT ticketID, 
status, 
COUNT(status) as count, 
statusName, 
'assigned' 
FROM ticket, department, status 
WHERE ticket.department = 100 
AND ticket.department = department.departID 
AND ticket.status = status.statusID 
AND assign is NOT NULL 
GROUP BY statusName 

該查詢獲取的未分配和以兩個不相交結果集的聯合形式分配的票證。