2014-09-03 106 views
4

我有两个表:item_status_log和items。 items表中有itemid,status和ordertype两列。 item_status_log表包含itemid,date_time,new_status和old_status。基本上,当我的程序中的状态发生变化时,记录会以旧状态,新状态和日期时间记录在item_status_log中。子查询使用来自外部查询的未分组列“i.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'的项目表中。

我在寻找这样的:

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 

回答

4

我想你只需要有条件聚集:

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; 
+0

完美!我不得不添加一个内部联接,因为ordertype在items表中,但是你让我走上了正确的轨道。谢谢! – 2014-09-03 02:50:48

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