如何使用MySQL和计数和排名

时间:2012-09-13 11:22:15

标签: mysql

我是MS-SQL开发人员,现在我使用此查询(MySQL)↓

SELECT A.place_idx,A.place_id,B.TODAY_CNT,C.TOTAL_CNT FROM CUSTOM_LIST 

AS A

INNER JOIN
(SELECT place_id,COUNT(place_id) AS TODAY_CNT from COUNT_TABLE where DATE(place_date) = DATE(NOW()) GROUP BY place_id)
AS B ON B.place_id=A.place_id

INNER JOIN
(SELECT place_id,COUNT(place_id) AS TOTAL_CNT from COUNT_TABLE GROUP BY place_id)
AS C ON C.place_id=A.place_id

结果是:

enter image description here

我想要这个:

enter image description here

2 个答案:

答案 0 :(得分:4)

尝试这样的事情:

SELECT ..., C.TOTAL_CNT, (@r := @r + 1) AS rank FROM CUSTOM_LIST, (SELECT  @r := 0) t
...
ORDER BY C.TOTAL_CNT DESC

整个查询:

SELECT A.place_idx,A.place_id,B.TODAY_CNT,C.TOTAL_CNT, (@r := @r + 1) AS rank 
FROM CUSTOM_LIST AS A, (SELECT  @r := 0) t

INNER JOIN
(SELECT place_id,COUNT(place_id) AS TODAY_CNT from COUNT_TABLE where DATE(place_date) = DATE(NOW()) GROUP BY place_id)
AS B ON B.place_id=A.place_id

INNER JOIN
(SELECT place_id,COUNT(place_id) AS TOTAL_CNT from COUNT_TABLE GROUP BY place_id)
AS C ON C.place_id=A.place_id

ORDER BY C.TOTAL_CNT DESC

如果我们在Total_COUNT中获得两个相同的值,该怎么办?

也许是这样的:

SELECT ..., (@last := C.TOTAL_CNT) AS TOTAL_CNT, 
  IF(@last = C.TOTAL_CNT, @r, @r := @r + 1) AS rank
FROM CUSTOM_LIST, (SELECT  @r := 0, @last := -1) t
...

答案 1 :(得分:-1)

<强>更新

RANK()OVER(按TOTAL_CNT DESC DESC订购)作为等级

在这里,我得到了另一个非常好的解决方案。:

SELECT A.place_idx,A.place_id,B.TODAY_CNT,C.TOTAL_CNT, RANK() OVER (ORDER BY TOTAL_CNT DESC) AS Rank FROM CUSTOM_LIST 

AS A

INNER JOIN
(SELECT place_id,COUNT(place_id) AS TODAY_CNT from COUNT_TABLE where DATE(place_date) = DATE(NOW()) GROUP BY place_id)
AS B ON B.place_id=A.place_id

INNER JOIN
(SELECT place_id,COUNT(place_id) AS TOTAL_CNT from COUNT_TABLE GROUP BY place_id)
AS C ON C.place_id=A.place_id