统计日期 2018-09-01 到2018-09-02
如果一个ItemID一天中有一个City的Stock为1 那么当天此ItemID的查询结果计为1
查询指定日期区间 所有ItemID查询结果的和
比如下表 2018-09-01的查询结果应该为2 2018-09-01的查询结果为3
指定日期区间内查询结果应该为5
你描述的我不明白,但我写一条sql你看看能不能用,像你这种要求和的一般会用刀sum函数和group by子句。
select date, sum(stock) as itemid, city from table where date >= '2018-09-01' and date <= '2018-09-02' group by date, city
select count(*)
from
(select *
from table
where Date >= '2018-09-01' and Date <= '2018-09-02' and Stock = 1
group by Date,ItemID) aa
试看看以下的SQL是否符合你的需求,具体的思路是抓出Stock为1的列,先依Date及Item Group起来。
最外面再包一层,依Date Group即可。
Select [Date], Count(1) SumOfStock
From (
Select [Date], ItemID, Count(1) Stock
From Table
Where Stock = 1
Group By [Date], ItemID
) Stock
Where Stock.SumOfStock > 0
Group By [Date]
试下 count(distinct ItemID)
mysql:理解一下
select '2018-09-01至2018-09-02' as '区间', count(*) from
(
select * from csdn.csdn_181011
where Date between str_to_date('2018-09-01','%Y-%m-%d') and str_to_date('2018-09-02','%Y-%m-%d')
and Stock = 1
group by Date, ItemId, Stock
) a;
可以试一下括号里的sql,同时要去理解一下group by
select ItemID,Date,count(Stock)
from table
where Date >= '2018-09-01' and Date <= '2018-09-02' and Stock = 1
group by Date,ItemID
SELECT date,itemid,MIN(Stock) Stock,MIN(City) City FROM table
WHERE Stock=1 AND date BETWEEN '2018-09-01' AND '2018-09-02' GROUP BY date,itemid