2014-09-03 104 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