GROUP BY不在票上工作

时间:2016-09-11 06:09:41

标签: sql sql-server

我的查询出错了:

  

Msg 8120,Level 16,State 1,Line 3
  专栏' CrmDesk.Ticket.Id'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

这是我的疑问:

Select * 
from CrmDesk.Ticket 
where TicketCode in (select DISTINCT(TicketCode) 
                     from CrmDesk.Ticket 
                     where ReciverUserId ='3A4AA2F4-75C8-4725-8F16-81F34158258B')
group by TicketCode 

此查询具有相同的错误

select * 
from CrmDesk.Ticket 
group by TicketCode

问题是什么,我该如何解决?

4 个答案:

答案 0 :(得分:0)

您应该在选择列表中的group by子句中包含列。

如果您想检查具有相同主题和评论的同一张票,请使用以下脚本..

  Select *
  From crmdesk.ticket t
    Join ( select t1.ticketcode,t1.subject,t1.comment
               From crmdesk.ticket t1
               Group by t1.ticketcode,t1.subject,t1.comment
               Having count(t1.id) >1) t1-- assuming you have an ID column, if not replace with ticketcode or any other relevant column 
             On t.ticketcode=t1.ticketcode
                  And t.subject=t1.subject
                  And t.comment=t1.comment

答案 1 :(得分:0)

为什么在这个select语句中甚至需要一个子查询和GROUP BY子句? 对于select语句,您可以使用以下查询:

select * 
from CrmDesk.Ticket 
where TicketCode  
where ReciverUserId ='3A4AA2F4-75C8-4725-8F16-81F34158258B'

答案 2 :(得分:0)

您必须确定需要按票证分组的原因吗?

如果您想获得不同的票证代码值:

Select TicketCode
from CrmDesk.Ticket 
where ReciverUserId ='3A4AA2F4-75C8-4725-8F16-81F34158258B'
group by TicketCode

如果你想数点什么:

Select TicketCode, COUNT(ID)
from CrmDesk.Ticket 
where ReciverUserId ='3A4AA2F4-75C8-4725-8F16-81F34158258B'
group by TicketCode

如果您只想要不同的值(没有重复):

Select distinct Subject, Comment, TicketCode
from CrmDesk.Ticket 
where ReciverUserId ='3A4AA2F4-75C8-4725-8F16-81F34158258B'

或者:

Select Subject, Comment, TicketCode
from CrmDesk.Ticket 
where ReciverUserId ='3A4AA2F4-75C8-4725-8F16-81F34158258B'
group by Subject, Comment, TicketCode

答案 3 :(得分:0)

在查询中使用group by时,必须使用以下一种聚合函数:summinmaxcount ,. ..