1

I have two tables for saving user queries in my site. One for Tickets and the other for Ticket Replies. What I want is to count total tickets + total replies + total tickets with different status's. I can successfully count total tickets and total replies but I am having problem with counting ticket status's.

The problem: When I use following query, it shows total new and open tickets but as the query is a JOIN query, it shows total status's of all rows (which means it's showing sum of status's for all replies and not all tickets).

SELECT  COUNT(tr.ticketid) totalReplies, 
    COUNT(DISTINCT(t.ticketid)) totalTickets,
        SUM(CASE WHEN t.status='Open' THEN 1 END) totalOpen,
        SUM(CASE WHEN t.status='Close' THEN 1 END) totalClose
FROM `tbl_ticket` t 
INNER JOIN `tbl_ticket_reply` tr ON tr.ticketid = t.ticketid

Hope I am making myself clear. I will explain it with an example. Let's say we have total following records:

total tickets: 10
total replies: 20

Let's say, half tickets are opened and half closed. Then it should show 5 open, 5 closed. But instead, it gives 10 open and 10 closed.

Update: I do not want to group my query by status as it would then distribute my total tickets among status's.

Any help? Thanks

2 Answers 2

2

this code may work for your data

SELECT  
COUNT(t.ticketid) AS totaltickets, 
SUM(CASE WHEN t.status='Open' THEN 1 END) AS totalopen, 
SUM(CASE WHEN t.status='Close' THEN 1 END) AS totalclose
,(
    SELECT COUNT(*) FROM tbl_ticket t 
    LEFT JOIN tbl_ticket_reply tr ON t.ticketid=tr.ticketid
) AS total_replies
FROM tbl_ticket t 
Sign up to request clarification or add additional context in comments.

Comments

1

Use GROUP BY status in your query.

You need something like:

select count(tickets) tkt_cnt, count(replies) rep_cnt from mytable
group by status

On your query, following change should be working.

SELECT
    COUNT(tr.ticketid) totalReplies, 
    COUNT(DISTINCT(t.ticketid)) totalTickets,
    SUM(CASE WHEN t.status='Open' THEN 1 ELSE 0 END) totalOpen,
    SUM(CASE WHEN t.status='Close' THEN 1 ELSE 0 END) totalClose
FROM `tbl_ticket` t 
INNER JOIN `tbl_ticket_reply` tr ON tr.ticketid = t.ticketid
GROUP BY t.status

1 Comment

Hi. Thanks. But, I don't want to group by status as it would then show 2 rows for total tickets and total replies. I don't want my tickets and replies to be distributed among status.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.