这是我的数据:
CREATE TABLE SALES (
ts TIMESTAMP NOT NULL,
name VARCHAR(50) NOT NULL,
quantity INTEGER,
price DECIMAL(2,2)
);
INSERT INTO SALES VALUES
("2017-02-08 13:38:02", "apple", 6, 4.38),
("2017-02-08 13:38:02", "banana", 10, 3.50),
("2017-02-08 13:38:02", "orange", 8, 2.98),
("2017-02-08 09:21:52", "banana", 6, 2.67),
("2017-02-08 09:21:52", "pear", 3, 2.00),
("2017-02-07 15:21:32", "apple", 6, 4.38),
("2017-02-07 15:21:32", "banana", 6, 2.67),
("2017-02-07 11:03:16", "orange", 8, 2.98),
("2017-02-07 11:03:16", "banana", 4, 1.17);
我想获得今天但不是昨天销售的商品。
我可以使用以下方法将它们分为两列:
select
name,
SUM(case when strftime('%Y-%m-%d', sales_ts) = '2017-02-08' then quantity else 0 end) as today,
SUM(case when strftime('%Y-%m-%d', sales_ts) = '2017-02-07' then quantity else 0 end) as yday
from sales
group by name
having yday = 0
结果:
| name | today | yday
---------------------
| pear | 3 | 0
但我怎么能得到2列,1为名称,1为名为#34; sold_today_but_not_yday"有真/假值吗?那可能吗? (最好不使用子查询)。
答案 0 :(得分:1)
您可以使用case
:
select name,
(case when SUM(case when strftime('%Y-%m-%d', sales_ts) = '2017-02-08' then quantity else 0 end) > 0 and
SUM(case when strftime('%Y-%m-%d', sales_ts) = '2017-02-07' then quantity else 0 end) = 0
then 1 else 0
end) as isTodayNotYesterday
from sales
group by name;