我需要计算特定日期的所有FirstExtracted
,并且我需要计算同一日期的所有LastExtracted
。所以,对于今天,我需要所有FirstExtracted
和LastExtracted
等于2012-10-24
。
到目前为止,这是我所拥有的,但它没有提出LastExtracted
。它输出LastExtracted
与FirstExtracted
相同的计数:
(SELECT LastExtracted,FirstExtracted,
COUNT(FirstExtracted) AS FirstCount,
COUNT(LastExtracted) AS LastCount,
DATE_FORMAT(`LastExtracted`,'%Y-%m-%d') AS Lastdate,
DATE_FORMAT(`FirstExtracted`,'%Y-%m-%d') AS Firstdate
FROM results
WHERE DATE_FORMAT(`FirstExtracted`,'%Y-%m-%d') = DATE_FORMAT(`LastExtracted`,'%Y-%m-%d'))
UNION ALL
(SELECT LastExtracted,FirstExtracted,
COUNT(FirstExtracted) AS FirstCount,
COUNT(LastExtracted) AS LastCount,
DATE_FORMAT(`LastExtracted`,'%Y-%m-%d') AS Lastdate,
DATE_FORMAT(`FirstExtracted`,'%Y-%m-%d') AS Firstdate
FROM results
WHERE DATE_FORMAT(`FirstExtracted`,'%Y-%m-%d') = DATE_FORMAT(`LastExtracted`,'%Y-%m-%d') GROUP BY Firstdate)
ORDER BY Firstdate DESC
LIMIT 20
也许我应该使用内连接?
更新: 所以使用你的查询我做了一些更改,让它现在为我做其他事情。如果你看看这个页面我把查询放了
semesterold.com/code2.html
我想要计算所有头衔和GROUP BY艺术家。这将是一个数组。那么我希望子查询按照艺术家匹配的searchtype计算。所以如果db有akon,rihanna,chris brown。我想要计算每个艺术家有多少个头衔,比如akon有100个。然后我想显示标题的数量,然后计算这100个标题中有多少是google,bing,akon特定的网站等等。
答案 0 :(得分:0)
我建议在您的查询中添加DISTINCT
:
(SELECT LastExtracted,FirstExtracted,
COUNT(DISTINCT FirstExtracted) AS FirstCount,
COUNT(DISTINCT LastExtracted) AS LastCount,
DATE_FORMAT(`LastExtracted`,'%Y-%m-%d') AS Lastdate,
DATE_FORMAT(`FirstExtracted`,'%Y-%m-%d') AS Firstdate
FROM results
WHERE DATE_FORMAT(`FirstExtracted`,'%Y-%m-%d') = DATE_FORMAT(`LastExtracted`,'%Y-%m-%d'))
UNION ALL
(SELECT LastExtracted,FirstExtracted,
COUNT(DISTINCT FirstExtracted) AS FirstCount,
COUNT(DISTINCT LastExtracted) AS LastCount,
DATE_FORMAT(`LastExtracted`,'%Y-%m-%d') AS Lastdate,
DATE_FORMAT(`FirstExtracted`,'%Y-%m-%d') AS Firstdate
FROM results
WHERE DATE_FORMAT(`FirstExtracted`,'%Y-%m-%d') = DATE_FORMAT(`LastExtracted`,'%Y-%m-%d') GROUP BY Firstdate)
ORDER BY Firstdate DESC
LIMIT 20
答案 1 :(得分:0)
我会使用union分别获取两个结果(FirstExtracted和LastExtracted),然后使用子查询合并它们。
SELECT
sub.date, sum(sub.FirstCount) AS FirstCount,
sum(sub.LastCount) AS LastCount
FROM (
SELECT
DATE_FORMAT(`FirstExtracted`,'%Y-%m-%d') AS date,
COUNT(FirstExtracted) AS FirstCount, 0 AS LastCount
FROM results
GROUP BY date
UNION ALL
SELECT
DATE_FORMAT(`LastExtracted`,'%Y-%m-%d'),
0, COUNT(LastExtracted)
FROM results
GROUP BY date
) AS sub
GROUP BY sub.date
假设您今天首次提取了220个条目,而今天最近提取的条目为292个。在其他日期的条目中,这将给你:
+------------+------------+-----------+
| date | FirstCount | LastCount |
+------------+------------+-----------+
| 2012-10-24 | 220 | 292 |
+------------+------------+-----------+
更新仅UNION
将为您提供以下结果。注意零占位符。
+------------+------------+-----------+
| date | FirstCount | LastCount |
+------------+------------+-----------+
| 2012-10-24 | 220 | 0 |
+------------+------------+-----------+
| 2012-10-24 | 0 | 292 |
+------------+------------+-----------+