简体   繁体   中英

How to count multiple columns in a MySQL query

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

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

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM