SQL查询计数相同的值并在单独的列中显示值

时间:2018-09-10 14:03:05

标签: sql sql-server

我的表有客户退货,并链接到与客户表链接的票证表。退货表和客户表之间没有直接关系。

Return_Table :(列)

INEDX_Return,
CustomerName, 
DateAdded

我想计算一个月内同一个名字出现的次数

预期结果:

Customer Name     |  No Time Name Appears
__________________|________________________
  customer 1      |  34
  customer 2      |  12

我是这样写的,它很接近,但是给我的值是错误的:(“ customer_ID”不是FK或int名称)

SELECT TOP 20 COUNT(Return_Table.Customer_ID) AS TimesReturned, 
       Return_Table.Customer_ID
FROM Return_Table         
WHERE Return_Table.DateAdded >= DATEADD(month, -1, GETDATE()) 
GROUP BY Return_Table.Customer_ID

2 个答案:

答案 0 :(得分:1)

我想你可以试试看。

SELECT CustomerName,
     COUNT(*) AS TimesReturned
FROM Return_Table         
WHERE Return_Table.DateAdded >= DATEADD(month, -1, GETDATE()) 
GROUP BY CustomerName

答案 1 :(得分:1)

所需的查询使用简单的聚合函数。您需要计算每个名称出现的实例数。参见:https://www.dofactory.com/sql/group-by

select CustomerName, count(CustomerName) from 
Return_Table 
where DateAdded between START_DATE AND END_DATE
GROUP BY CustomerName