MySQL解释器调用查询而不使用聚合函数作为聚合查询

时间:2017-09-25 04:30:15

标签: mysql

我正在努力解决this HackerRank SQL coding challenge。我们有两个表,一个名为Hackers,列hacker_idname,另一个名为Submissions,列submission_datesubmission_id,{{1 }和hacker_id

我提交的一个解决问题的查询是:

score

然而,我收回了错误:

SELECT  es.date, es.count, m.hacker_id, m.name, m.score
FROM 
(
    SELECT submission_date as date, COUNT(hacker_id) as count
    FROM (
        SELECT submission_date, COUNT(submission_id) as count, hacker_id
        FROM Submissions 
        GROUP BY submission_date, hacker_id
    ) f 
    HAVING count >=1
) es
JOIN (
    SELECT s.submission_date as date, s.hacker_id, h.name, s.score
    FROM Submissions s 
    JOIN Hackers h ON h.hacker_id = s.hacker_id 
    JOIN (SELECT submission_date, MAX(score) as score FROM Submissions GROUP BY submission_date) foo ON foo.submission_date = s.submission_date
    WHERE s.score = foo.score 
) m 
ON es.date = m.date
ORDER BY es.date

这让我很困惑,因为我在查询中没有使用聚合函数。为什么解释器会出现这个错误,我应该考虑解决它?

1 个答案:

答案 0 :(得分:0)

第一个子查询中有两列名为count。一个是字段submission_id的计数,第二个是hacker_id的计数。据我所知,查询需要执行submission_dates的选择,其中count大于或等于1.因此,取决于假定哪个计数大于或等于1,查询可能会被重写如下:

1)如果需要count(submission_id)大于或等于1:

SELECT  es.date, es.count, m.hacker_id, m.name, m.score
FROM 
(
SELECT submission_date as date, COUNT(hacker_id) as count
FROM (
    SELECT submission_date, COUNT(submission_id) as count, hacker_id
    FROM Submissions 
    GROUP BY submission_date, hacker_id
) f 
WHERE f.count >=1
GROUP BY submission_date
) es
JOIN (
   SELECT s.submission_date as date, s.hacker_id, h.name, s.score
   FROM Submissions s 
JOIN Hackers h ON h.hacker_id = s.hacker_id 
JOIN (SELECT submission_date, MAX(score) as score FROM Submissions GROUP BY submission_date) foo ON foo.submission_date = s.submission_date
WHERE s.score = foo.score 
) m 
ON es.date = m.date
ORDER BY es.date

2)count(hacker_id)大于或等于1:

SELECT  es.date, es.count, m.hacker_id, m.name, m.score
FROM 
(
SELECT submission_date as date, COUNT(hacker_id) as count
FROM (
    SELECT submission_date, COUNT(submission_id) as count, hacker_id
    FROM Submissions 
    GROUP BY submission_date, hacker_id
) f 
GROUP BY submission_date
HAVING count(hacker_id) >= 1
) es
JOIN (
   SELECT s.submission_date as date, s.hacker_id, h.name, s.score
   FROM Submissions s 
JOIN Hackers h ON h.hacker_id = s.hacker_id 
JOIN (SELECT submission_date, MAX(score) as score FROM Submissions GROUP BY submission_date) foo ON foo.submission_date = s.submission_date
WHERE s.score = foo.score 
) m 
ON es.date = m.date
ORDER BY es.date

问题在于子查询中使用了聚合函数计数(hacker_id)而没有" group by"列#34; submission_date"在那里定义为非聚合列。 我还不确定sql-query在逻辑上是否正确。