简体   繁体   中英

How to convert this query for SQL SERVEr

SQLSTATE[42000]: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Column 'ws_ticket.tkt_assunto' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

QUERY

SELECT COUNT(tkt.tkt_id) as messages, tkt.tkt_id, tkt.tkt_assunto, tkt.tkt_departamento, tkt.tkt_prioridade, tkt.tkt_content, tkt.tkt_data_create, tkt.tkt_data_close, tkt.tkt_status
FROM ws_ticket tkt LEFT JOIN
     ws_ticket_reply alls
     ON alls.tkt_id = tkt.tkt_id
WHERE tkt.tkt_status IN (1,2) AND tkt.user_id = :id
GROUP BY tkt.tkt_id
ORDER BY tkt.tkt_data_create DESC

Just include all the non-aggregated columns in the group by :

SELECT COUNT(tkt.tkt_id) as messages, tkt.tkt_id, tkt.tkt_assunto, 
       tkt.tkt_departamento, tkt.tkt_prioridade, tkt.tkt_content, 
       tkt.tkt_data_create, tkt.tkt_data_close, tkt.tkt_status
FROM ws_ticket tkt LEFT JOIN
     ws_ticket_reply alls
     ON alls.tkt_id = tkt.tkt_id
WHERE tkt.tkt_status IN (1,2) AND tkt.user_id = :id
GROUP BY tkt.tkt_id, tkt.tkt_assunto, 
         tkt.tkt_departamento, tkt.tkt_prioridade, tkt.tkt_content, 
         tkt.tkt_data_create, tkt.tkt_data_close, tkt.tkt_status
ORDER BY tkt.tkt_data_create DESC

In your query you are only grouping by tkt_id this means that for any other column in your select they either need to have the exact same value in every row or have some sort of aggregate applied to them (eg your count).

You need to understand what you are grouping together.

With your current query either you only display messages and id and nothing else:

SELECT COUNT(tkt.tkt_id) as messages, 
       tkt.tkt_id
FROM   ws_ticket tkt 
LEFT JOIN ws_ticket_reply alls ON alls.tkt_id = tkt.tkt_id
WHERE  tkt.tkt_status IN (1,2) 
AND    tkt.user_id = :id
GROUP BY tkt.tkt_id
ORDER BY tkt.tkt_data_create DESC

or include the other columns in the group by

SELECT COUNT(tkt.tkt_id) as messages, 
       tkt.tkt_id, 
       tkt.tkt_assunto, 
       tkt.tkt_departamento,  
       tkt.tkt_prioridade, 
       tkt.tkt_content, 
       tkt.tkt_data_create, 
       tkt.tkt_data_close, 
       tkt.tkt_status
FROM   ws_ticket tkt 
LEFT JOIN ws_ticket_reply alls ON alls.tkt_id = tkt.tkt_id
WHERE  tkt.tkt_status IN (1,2) 
AND    tkt.user_id = :id
GROUP BY tkt.tkt_id, 
         tkt.tkt_assunto, 
         tkt.tkt_departamento, 
         tkt.tkt_prioridade, 
         tkt.tkt_content, 
         tkt.tkt_data_create, 
         tkt.tkt_data_close, 
         tkt.tkt_status
ORDER BY tkt.tkt_data_create DESC

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