具有分组依据的MySQL唯一免除案例

时间:2016-11-29 19:03:39

标签: mysql sql group-by

我有一组数据列出了用户更改产品的时间,我们会查看更改产品的人员,时间,旧成本和新成本以及百分比价格差异。

我想使用group by,where statement或case to group by并排除过滤掉更改的产品,这些更改是在同一天发生的,并导致原始价格保持不变。

所以我要排除的情况如下:

| product  | Changed By | Old Price | New Price | % diff | Day Changed |
|----------|------------|-----------|-----------|--------|-------------|
| blue hat | me         |     94.00 |     95.00 |   1.05 | 2016-11-28  |
| blue hat | me         |     95.00 |     94.00 |   1.05 | 2016-11-28  |

有关如何使用MySql执行此操作的任何想法吗?

1 个答案:

答案 0 :(得分:0)

这是一个工作版本,适用于任何想要使用子查询,其中和分组来完成此操作的人。

此查询查看用户在1天的范围内对项目成本的更改,其中它从“昨天”中提取所有结果。它列出了当天的一个asc和一个desc的所有更改,并比较了这种方式的价格变化。如果它们从最旧的变化到最新的变化是相同的那么它就是免除的。

SELECT 
    us.Name,
    it.Name,
    pal.CS_PA_Line_Supplier__c as supplier_name,
    newest.NewValue as new_value,
    oldest.OldValue as old_value,
    ((newest.NewValue - oldest.OldValue) / oldest.OldValue) * 100 as Percentage
FROM    
(
    SELECT Id, Name, KNDY4__Item__c, CS_PA_Line_Supplier__c
    FROM KNDY4__Contract_Line__c
) pal

LEFT JOIN 
(
    SELECT * 
    FROM 
    (
        SELECT 
            ParentId,
            CreatedById,
            CreatedDate,
            Field,
            NewValue
        FROM KNDY4__Contract_Line__History 
        WHERE CreatedDate >= CURDATE() - INTERVAL 1 DAY
            AND CreatedDate < CURDATE() 
            AND Field='KNDY4__Negotiated_Price__c' 
        ORDER BY CreatedDate DESC
    ) cd 
    GROUP BY ParentId
) newest 
    ON newest.ParentId=pal.Id

LEFT JOIN 
(
    SELECT * FROM (
        SELECT 
            ParentId,
            OldValue
        FROM KNDY4__Contract_Line__History 
        WHERE CreatedDate >= CURDATE() - INTERVAL 1 DAY
            AND CreatedDate < CURDATE() 
            AND Field='KNDY4__Negotiated_Price__c' 
        ORDER BY CreatedDate ASC
    ) cd 
    GROUP BY ParentId 
) oldest 
    ON oldest.ParentId=pal.Id

LEFT JOIN 
(
    SELECT Id, Name
    FROM User
) us 
    ON us.Id = newest.CreatedById

LEFT JOIN 
(
    SELECT Id,Name 
    FROM KNDY4__Item__c
) it 
    ON it.Id=pal.KNDY4__Item__c

WHERE newest.ParentId IS NOT NULL 
    AND oldest.OldValue IS NOT NULL 
    AND newest.NewValue != oldest.OldValue
GROUP BY pal.KNDY4__Item__c, pal.CS_PA_Line_Supplier__c
ORDER BY it.Name ASC