【发布时间】:2014-09-03 02:41:11
【问题描述】:
我有两个表: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 列,它分解了有多少项目在“库存”和“订单”表中具有状态。
我正在寻找这个:
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
【问题讨论】:
-
使用 count(1) 而不是 count(*) 不需要检查所有列