如何在select语句中使用嵌套选择执行计数

时间:2015-08-27 21:57:24

标签: mysql count nested-loops

所以这就是问题所在。我正在尝试编写一个新的填充报告,因为内置的报告不够好...我正在尝试运行一个select语句来返回两者,计算特定月份的项目订购次数,然后还计算完全开票/发货的次数。

这段代码显然是错误的,我目前还限制只考虑2015年的AUG,但这只是为了简化测试期间的结果。

我无法弄清楚如何进行第二次计数......这就是我正在尝试的(大脑因每个循环逻辑而过时):

select inv_mast.item_id, 
       inv_mast.item_desc,
       "YEAR" = year(oe_line.required_date), 
       "MONTH" = month(oe_line.required_date),
       "ORDERS" = count(1),
       "HITS" = (
                  select count(1)
                  from invoice_line
                where invoice_line.order_no = oe_line.order_no 
                  and invoice_line.oe_line_number = oe_line.line_no
                  and invoice_line.qty_shipped = oe_line.qty_ordered
               )            


from oe_line, 
     inv_mast,
     inv_loc

where inv_mast.inv_mast_uid = oe_line.inv_mast_uid 
  and inv_mast.delete_flag = 'N'
  and inv_mast.inv_mast_uid = inv_loc.inv_mast_uid
  and inv_loc.location_id = '101'

  and year(oe_line.required_date) = '2015' 
  and month(oe_line.required_date) = '8'


group by inv_mast.item_id, 
         inv_mast.item_desc,
         year(oe_line.required_date), 
         month(oe_line.required_date)

order by inv_mast.item_id

1 个答案:

答案 0 :(得分:0)

对我而言,您似乎可以重写查询以在invoice_line表上使用左连接。没有任何适当的测试数据我不能保证它是正确的,但我认为它应该是。

除了左连接之外,我还改为显式连接并移动了别名,因为我认为MySQL不支持alias = column语法。

select inv_mast.item_id, 
       inv_mast.item_desc,
       year(o.required_date) as "YEAR", 
       month(o.required_date) as "MONTH",
       count(1) as "ORDERS",
       count(invoice_line.order_no) as "HITS"
from oe_line o
join inv_mast on inv_mast.inv_mast_uid = o.inv_mast_uid 
join inv_loc  on inv_mast.inv_mast_uid = inv_loc.inv_mast_uid
left join invoice_line on invoice_line.order_no = o.order_no 
                      and invoice_line.oe_line_number = o.line_no
                      and invoice_line.qty_shipped = o.qty_ordered
where inv_mast.delete_flag = 'N'
  and inv_loc.location_id = '101'
  and year(o.required_date) = '2015' 
  and month(o.required_date) = '8'

group by inv_mast.item_id, 
         inv_mast.item_desc,
         year(o.required_date), 
         month(o.required_date)

order by inv_mast.item_id;