在SQL中使用COUNT和MAX

时间:2013-11-26 19:31:50

标签: sql sql-server-2012

我正在尝试查找哪个客户的交易次数最多。事务表具有一个外键,用于标识与客户的每个事务。我目前的代码如下:

WITH Customers as (
   SELECT
       [CustName] as 'Customer',
       [TRANSACTION].[CustID] as 'Total # of Transactions'
   FROM [dbo].[CUSTOMER]
   INNER JOIN [dbo].[TRANSACTION]
   ON [CUSTOMER].[CustID] = [TRANSACTION].[CustID]
)
SELECT *
FROM Customers
WHERE 'Total # of Transactions' = (SELECT MAX('Total # of Transactions') FROM Customers);

有两件事是错的: 1)代码的后半部分不接受Total#of Transactions'。如果我要将它重命名为单个单词,我可以将其视为变量。 2)我的最后一个SELECT语句给出了客户及其所有交易的结果,但没有给我COUNT这些交易。我不确定如何将COUNT与MAX结合使用。

3 个答案:

答案 0 :(得分:1)

首先选择客户和交易计数。

然后选择最大的一个。

他们将您的选择限制为该项目。

从内到外工作。

SELECT *
FROM Customers
WHERE CustID =
(
  SELECT TOP 1 CustID 
  FROM (SELECT CustID, COUNT(*) AS TCOUNT
        FROM TRANSACTIONS
        GROUP BY CustID) T
  ORDER BY T.TCOUNT DESC
) TT

答案 1 :(得分:1)

这应该可以为您提供所需的一切。要让顶级客户只需将Top 1添加到选择

WITH Customers as (
   SELECT
       [CustName] as Name
   FROM [dbo].[CUSTOMER]
   INNER JOIN [dbo].[TRANSACTION]
   ON [CUSTOMER].[CustID] = [TRANSACTION].[CustID]
)

-- to get count of transactions
Select Count(*) as count, Name
FROM Customers
Group by Name
Order By Count(*) desc

答案 2 :(得分:0)

您的内部表只返回CustID作为交易总数?您需要首先查找每个客户的总数。另外对于列,您可以使用[Name],当您使用撇号时,它认为您正在比较字符串。如果您想要返回所有具有最高计数的客户,您可以使用:

WITH TransactionCounts as (
   SELECT
       CustID,
       COUNT(*) AS TransactionCount
   FROM [dbo].[TRANSACTION]
   GROUP BY CustID
)
SELECT TOP 1 CUSTOMER.*, TransactionCount
FROM TransactionCounts
    INNER JOIN CUSTOMER ON CUSTOMER.CustID = TransactionCounts.CustId
ORDER BY TransactionCount DESC

-- alternate to select all if multiple customers are tied for highest count
--WHERE TransactionCount = (SELECT MAX(TransactionCount) FROM TransactionCounts)