我有两个表:item_status_log和items。 items表具有itemid,status和ordertype列。 item_status_log表具有itemid,date_time,new_status和old_status。基本上,当在我的程序中更改状态时,会在item_status_log中记录一条记录,其中包含旧状态,新状态和date_time。
我想要的是能够查看按更新日期分组的项目表。我有以下sql工作完美:
select to_char(date_time, 'MM-DD-YYYY') as "Shipment Date", count(*) as "TOTAL Items"
from item_status_log i where old_status = 'ONORDER'
group by "Shipment Date"
order by "Shipment Date" desc
这给了我
Shipment Date | TOTAL Items
------------------------------
09/02/2014 | 4
09/01/2014 | 23
但是,我想在上面的表中添加2列,这样可以分解“INVENTORY”和“ORDER”的items表中有多少项具有状态。
我正在寻找:
Shipment Date | TOTAL Items | Inventory | Ordered
---------------------------------------------------------
09/02/2014 | 4 | 3 | 1
09/01/2014 | 23 | 20 | 3
这是我正在尝试的,但是让'子查询使用未分组的列“i.date_time”来自外部查询'错误
select to_char(date_time, 'MM-DD-YYYY') as "Shipment Date", count(*) as "TOTAL Items",
(select count(*) from item_status_log t
where date(t.date_time) = date(i.date_time) and itemid in (select itemid
from items where ordertype = 'ORDER')) as "Customer",
(select count(*) from item_status_log t
where date(t.date_time) = date(i.date_time) and itemid in (select itemid
from items where ordertype = 'INVENTORY')) as "Inventory"
from item_status_log i where old_status = 'ONORDER'
group by "Shipment Date"
order by "Shipment Date" desc
答案 0 :(得分:5)
我认为你只需要条件聚合:
select to_char(date_time, 'MM-DD-YYYY') as "Shipment Date", count(*) as "TOTAL Items",
sum(case when i.ordertype = 'ORDER' then 1 else 0 end) as NumOrders,
sum(case when i.ordertype = 'INVENTORY' then 1 else 0 end) as NumInventory
from item_status_log il join
items i
on il.itemid = i.itemid
where old_status = 'ONORDER'
group by "Shipment Date"
order by "Shipment Date" desc;
答案 1 :(得分:0)
尝试:
select to_char(date_time, 'MM-DD-YYYY') as "Shipment Date",
count(*) as "TOTAL Items",
sum(case when ordertype = 'INVENTORY' then 1 else 0 end) as "Inventory",
sum(case when ordertype = 'ORDER' then 1 else 0 end) as "Ordered"
from item_status_log i
where old_status = 'ONORDER'
group by "Shipment Date"
order by "Shipment Date" desc