Mysql Query - 如何获取每个类别和列的第一行及其比较?

时间:2017-05-01 09:10:55

标签: mysql

我需要一个mysql查询来查找哪个星期是最昂贵的一周(week_of_month)以及本周的多少 花费(WOM_AMT)比每年其他几个月对每个供应商

2 个答案:

答案 0 :(得分:1)

此查询将为您提供每周max次费用:

SELECT supplier, year, week_of_month, MAX(wom_amt)
FROM table t
GROUP BY supplier, year, week_of_month;

现在,为了将此金额与其余的SUM进行比较,您可以将此查询包装到外部查询中并计算SUM,例如:

SELECT a.supplier, a.year, a.week_of_month, a.wom_amt as 'max_amount',
(SELECT SUM(wom_amt) FROM table WHERE supplier = a.supplier AND year = a.year 
AND week_of_month = a.week_of_month AND wom_amt != a.wom_amt) as 'other_amounts'
FROM (SELECT supplier, year, week_of_month, MAX(wom_amt)
    FROM table t
    GROUP BY supplier, year, week_of_month) a;

答案 1 :(得分:-1)

我认为您所寻找的是MAXGROUP BY

这样的事情应该有效(未经测试):

SELECT 
    `Supplier`, 
    `Year`, 
    `Week_Of_Month`, 
    MAX(`WOM_AMT`) AS WOM_AMT
FROM `table`
GROUP BY `Supplier`, `Year`