MySQL查询由于日期不同而重复

时间:2018-07-18 20:15:00

标签: mysql sql

此查询准确给出了所要的内容,但问题是它不是我想要的,我似乎无法消除重复项,并且关于该主题的其他帖子似乎不适用。它用于销售报告,它从日历中提取日期,但是有时同一销售在需要回调时具有多个日历事件。

日历表只有ID,标题,位置,开始,报价字段,其余的来自quoterequests,这是MySQL。

SELECT qr.ID AS ID, 
c.ID AS CalendarID, 
DATE_FORMAT(QuoteDate,'%m-%d-%Y') AS QuoteDate, 
DATE_FORMAT(`Start`,'%m-%d-%Y') AS VerDate, 
TIME_FORMAT(`Start`,'%h:%i %p') AS VerTime, 
Name, MakeModel, CONCAT_WS('-',Prefix, Telephone) AS Phone, 
Email, 
Address, 
City, 
State, 
Zipcode, 
MilesQuoted, 
AmtQuoted, 
AmtCharged, 
ServiceFee 
FROM quoterequests qr 

JOIN calendar c 
ON Quote = qr.ID 

WHERE AmtCharged > 0 
AND YEAR(`Start`) = 2015 
ORDER BY UNIX_TIMESTAMP(`Start`) ASC

2 个答案:

答案 0 :(得分:0)

信息不足以回答问题,但根据经验:

GROUP BY仅在将混合函数(最小,最大,计数等)与常规列混合使用时使用。它并不意味着要删除重复项。

要删除重复项,请使用numpy.repeat

答案 1 :(得分:0)

也许不必要地令人费解,但这似乎可以解决问题,在我当时,我意识到Quote显然是一个保留字,所以我反驳了它。事实证明,所指出的主要问题是缺少MIN,但我没有意识到它可以在多个地方使用。一旦这样做,它就会给出正确的结果:

SELECT 
        ID,
        DATE_FORMAT(QuoteDate,'%m-%d-%Y') AS QuoteDate,
        DATE_FORMAT(MIN(c.`Start`),'%m-%d-%Y') AS VerDate,
        TIME_FORMAT(MIN(c.`Start`),'%h:%i %p') AS VerTime,

        Name, MakeModel, CONCAT_WS('-',Prefix, Telephone) AS Phone,
        Email,
        Address,
        City,
        State,
        Zipcode,
        MilesQuoted,
        AmtQuoted,
        AmtCharged,
        ServiceFee

FROM quoterequests qr 

LEFT JOIN (SELECT `Quote`, 
                `Start`, 
                MIN(UNIX_TIMESTAMP(`Start`)) AS `TimeStamp`
                FROM calendar c
                WHERE YEAR(`Start`) = 2015 
                GROUP BY ID, `Quote`, `Start` 
                ORDER BY UNIX_TIMESTAMP(`Start`) ASC) AS c 
        ON qr.ID = c.`Quote` 
WHERE AmtCharged > 0 
AND YEAR(c.`Start`) = 2015 
GROUP BY `Quote` 
ORDER BY UNIX_TIMESTAMP(MIN(c.`Start`)) ASC