使用SUM()对多个列进行单遍SQL查询

时间:2018-02-02 17:28:23

标签: mysql

架构:

        Color rgbValue = Color.FromArgb(red, green, blue);
        String conversion = rgbValue.ToString();

        Form converterForm = new Form();
        converterForm.BackColor = rgbValue;

        RGB_Box.Text = String.Format("rgb({0},{1},{2})", red, green, blue);

当前SQL查询使用2次传递:

CREATE TABLE purchases (name varchar(20), units SMALLINT, ts int);
INSERT INTO purchases (name, units, ts) 
  VALUES
    ('John', 1, UNIX_TIMESTAMP('2017-01-03 12:00:00')),
    ('John', 1, UNIX_TIMESTAMP('2017-01-04 12:00:00')),
    ('John', 1, UNIX_TIMESTAMP('2018-01-01 12:00:00')),
    ('John', 1, UNIX_TIMESTAMP('2018-01-01 12:00:00')),
    ('Jill', 1, UNIX_TIMESTAMP('2018-01-01 12:01:00')),
    ('Jill', 1, UNIX_TIMESTAMP('2018-01-01 12:01:00')),
    ('Jill', 1, UNIX_TIMESTAMP('2016-02-20 12:01:00')),
    ('Jill', 1, UNIX_TIMESTAMP('2016-03-13 12:01:00')),            
    ('Jack', 1, UNIX_TIMESTAMP('2002-12-08 12:02:00')),
    ('Jean', 1, UNIX_TIMESTAMP('2005-12-11 12:03:00'));

结果如下:

SELECT * FROM 
    (SELECT
        name, SUM(units) as histPurchases
    FROM purchases
    WHERE ts 
        BETWEEN UNIX_TIMESTAMP('1990-01-01 00:00:00')
        AND UNIX_TIMESTAMP('2019-02-01 00:00:00')
    GROUP BY name) as hist
JOIN 
    (SELECT name, SUM(units) as currPurchases # those bought on the 1st of Jan 2018
        FROM purchases
        WHERE ts 
            BETWEEN UNIX_TIMESTAMP('2018-01-01 00:00:00')
            AND UNIX_TIMESTAMP('2018-01-02 00:00:00')
    GROUP BY name) as curr
ON (hist.name = curr.name);

有没有办法构建查询,以便只进行一次传递(理想情况下使用最新版本的MySQL)? 这是SQL fiddle

0 个答案:

没有答案