在Oracle SQL中连接两次相同的表

时间:2017-03-09 08:59:13

标签: sql oracle

我有这个查询,它计算我们的SOP应用程序中的订单数量是由我们的客户直接传输的,并按周编号分组数据。

Select To_Char(AUF_KOPF.ERFASS_DAT, 'IW') As "Week No",
  Count(AUF_KOPF.AUF_NR) As "Total Orders"
From AUF_KOPF AUF_KOPF
  Inner Join ORDER_TOTALS On AUF_KOPF.AUF_NR = ORDER_TOTALS.ORDER_NO
Where AUF_KOPF.KOPF_SACH In ('EDI', 'MODEM') And AUF_KOPF.ERFASS_DAT =
  '<|Current year|>'
Group By To_Char(AUF_KOPF.ERFASS_DAT, 'IW')
Order By "Week No"

结果:

Week No Total Orders
01  253
02  303
03  318
04  280
05  256
06  308
07  295
08  301
09  333
10  268

但我想要的是看到一个额外的列来计算所有其他订单,但是当我更改了查询时,它以0结果结束并且没有错误消息,所以我不确定我是什么做错了。

Select To_Char(AUF_KOPF.ERFASS_DAT, 'IW') As "Week No",
  Count(AUF_KOPF.AUF_NR) As EDI,
  Count(b.AUF_NR) As "Other"
From AUF_KOPF AUF_KOPF
  Inner Join ORDER_TOTALS On AUF_KOPF.AUF_NR = ORDER_TOTALS.ORDER_NO
  Inner Join AUF_KOPF b On b.AUF_NR = ORDER_TOTALS.ORDER_NO
Where AUF_KOPF.KOPF_SACH In ('EDI', 'MODEM') And AUF_KOPF.ERFASS_DAT =
  '<|Current year|>' And b.KOPF_SACH Not In ('EDI', 'MODEM') And
  b.ERFASS_DAT = '<|Current year|>'
Group By To_Char(AUF_KOPF.ERFASS_DAT, 'IW')
Order By "Week No"

结果:

Week No EDI Other

有人可以指出出了什么问题吗?我所做的就是再次加入表格,并颠倒了WHERE条款。

2 个答案:

答案 0 :(得分:1)

  

有人可以指出出了什么问题吗?

FROM   AUF_KOPF AUF_KOPF
       Inner Join ORDER_TOTALS
       On AUF_KOPF.AUF_NR = ORDER_TOTALS.ORDER_NO
       Inner Join AUF_KOPF b
       On b.AUF_NR = ORDER_TOTALS.ORDER_NO
Where  AUF_KOPF.KOPF_SACH In ('EDI', 'MODEM')
And    b.KOPF_SACH Not In ('EDI', 'MODEM')

没有任何数据很难确定,但我的猜测是没有同一ORDER_NO的{​​{1}}行同时KOPF_SACHIN ('EDI', 'MODEM') }。由于您正在执行NOT IN ('EDI', 'MODEM')并且订单不同时同时符合这两个条件,因此它们将被排除。您可以更改为使用INNER JOIN s。

或者您可以从LEFT OUTER JOIN子句中的过滤更改为WHERE聚合中的过滤:

COUNT

答案 1 :(得分:0)

您不需要两次加入相同的表。您可以使用ggplot(myData,aes(x=X,y=Y)) + geom_point(aes(size = sqrt(Z1), alpha = .5)) case

解决此问题
decode

添加一个样本数据

Select To_Char(AUF_KOPF.ERFASS_DAT, 'IW') As "Week No",
  Count(decode(AUF_KOPF.KOPF_SACH,'EDI', 1, 'MODEM',1)) As "Orders EDI or MODEM",
  Count(decode(AUF_KOPF.KOPF_SACH,'EDI', null, 'MODEM',null, 1)) As "Orders but EDI or MODEM",
  Count(AUF_KOPF.AUF_NR) As "total orders"
From AUF_KOPF AUF_KOPF
  Inner Join ORDER_TOTALS On AUF_KOPF.AUF_NR = ORDER_TOTALS.ORDER_NO
Where AUF_KOPF.ERFASS_DAT =
  '<|Current year|>'
 Group By To_Char(AUF_KOPF.ERFASS_DAT, 'IW')
 Order By "Week No"