【问题标题】:subquery uses ungrouped column "i.date_time" from outer query子查询使用来自外部查询的未分组列“i.date_time”
【发布时间】: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(*) 不需要检查所有列

标签: sql subquery


【解决方案1】:

我认为你只需要条件聚合:

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;

【讨论】:

  • 完美!我不得不添加一个内部连接,因为 ordertype 在 items 表中,但你让我走上了正确的轨道。谢谢!
【解决方案2】:

试试:

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

【讨论】:

    猜你喜欢
    • 2020-10-08
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    • 2020-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多