比较行值SQL

时间:2015-09-30 12:27:58

标签: mysql

我在表中列出了当前月份和上个月的值,其中Weekpart为WE(周末)和WD(工作日)

Weekpart    Months  AvrgApps    AvrgOffers  AvrgDisbursements

WE          201509  441         259          40

WE          201508  432         235          40

WD          201508  2218        1591        334

WD          201509  2267        1156        346

我需要比较月份的WD和WE值,如果当前月份值高于上个月,则返回1列;如果等于或低于上个月的值,则需要0,结果表看起来像

Weekpart Months AvrgApps AvrgOffers AvrgDisbursements
WE       201509 441          259         40

WE       201508 432          235         40

WD       201508 2218         1591        334

WD       201509 2267         1156        346

WE       201509 1             1          0

WD       201509 1             0          1

1 个答案:

答案 0 :(得分:0)

我猜你在找这样的东西?

SELECT  CONCAT(current.Months, '-', previous.Months) AS Months,
        IF(current.AvrgApps > previous.AvrgApps, 1, 0) AS AvrgApps,
        IF(current.AvrgOffers > previous.AvrgOffers, 1, 0) AS AvrgOffers,
        IF(current.AvrgDisbursements > previous.AvrgDisbursements, 1, 0) AS AvrgDisbursements
FROM (
    SELECT *
    FROM t
    WHERE Months = @current := (SELECT MAX(Months) FROM t)
) current
JOIN (
    SELECT *
    FROM t
    WHERE Months = (SELECT MAX(Months) FROM t WHERE Months < @current)
) previous ON current.Weekpart = previous.Weekpart

这将为您提供月份差异作为结果。我不确定你想要&#34; union&#34;它与数据表一起。