1

我有两个表:Customer 和 ParkingTransaction。我想展示最常使用地段的前 10 位客户。ParkingTrasaction 表中的“CustomerKey”是将 ParkingTransaction 连接到 Customer 的 FK。我编写了以下代码,它计算了 ParkingTransaction 表中最常用的 CustomerKey,它工作正常......

SELECT TOP 10 CustomerKey
, count(*) as 'Usage'
  FROM ParkingTransaction
  GROUP BY CustomerKey
  HAVING (count(CustomerKey) > 0)
  ORDER BY 'Usage' DESC

这是我的输出

输出

我面临的问题是:我想从 Customer 表中提取 FirstName 和 LastName 字段,而不是仅按 CustomerKey 排序。我已经搞砸了 JOINS,但还没有提出解决方案。

谢谢!

4

2 回答 2

1

MySQLLIMIT不使用TOP.

SELECT  a.FirstName, a.LastName,
        COUNT(*) as `Usage`
FROM    Customer a
        INNER JOIN ParkingTransaction b
            ON a.CustomerKey = b.CustomerKey
GROUP BY a.FirstName, a.LastName
ORDER BY `Usage` DESC
LIMIT 10

由于查询正在使用INNER JOIN,HAVING COUNT(*) > 0在这种情况下是不必要的。

于 2013-01-18T00:06:16.330 回答
1

这是一种方法:

SELECT CustomerKey, c.firstname, c.lastname, count(*) as 'Usage'
FROM ParkingTransaction pt join
     customer c
     on pt.customerkey = c.customerkey
GROUP BY pt.CustomerKey, c.firstname, c.lastname, 
ORDER BY 'Usage' DESC
limit 10
于 2013-01-18T00:11:14.337 回答