MYSQL ABS和按功能分组

时间:2015-07-07 05:57:44

标签: mysql group-by

当我执行不带GROUP BY

的代码时,我有这样的sql代码
SELECT CompanyName, TotalPremi
FROM (`tblPackage`)
INNER JOIN `tblCompany` ON `tblPackage`.`CompanyID` = `tblCompany`.`CompanyID`
WHERE `tblPackage`.`PackageType` =  '2'
AND `tblPackage`.`IsActive` =  '1'
ORDER BY abs(tblPackage.TotalPremi - 150000)

结果将是

CompanyName | TotalPremi
将军| 150000
将军| 100000
将军| 200000
将军| 250000
Verista | 250000

我如何使用CompanyName进行分组? 我试过这段代码

SELECT CompanyName, TotalPremi
FROM (`tblPackage`)
INNER JOIN `tblCompany` ON `tblPackage`.`CompanyID` = `tblCompany`.`CompanyID`
WHERE `tblPackage`.`PackageType` =  '2'
AND `tblPackage`.`IsActive` =  '1'
GROUP BY CompanyName
ORDER BY abs(tblPackage.TotalPremi - 150000)

当我使用此代码时,ABS函数无效。

结果将显示

CompanyName | TotalPremi
将军| 100000
Verista | 250000

我的预期结果
公司名称| TotalPremi
将军| 150000
Verista | 250000

1 个答案:

答案 0 :(得分:0)

如果您想获得评论中提到的结果,可以直接使用此SQL。

                SELECT CompanyName, TotalPremi
            FROM (`tblPackage`)
            INNER JOIN `tblCompany` ON `tblPackage`.`CompanyID` = `tblCompany`.`CompanyID`
            WHERE `tblPackage`.`PackageType` =  '2'
            AND `tblPackage`.`IsActive` =  '1'
            AND TotalPremi BETWEEN 140000 AND 170000
            GROUP BY CompanyName
            ORDER BY CompanyName, TotalPremi
            ;

如果可以,请告诉我。