使用两个限制相同的表无法获得正确的结果

uqzxnwby  于 2021-07-29  发布在  Java
关注(0)|答案(2)|浏览(223)

1) 我有四个字段,如材料编号,项目编号,数量在一个表和日期在另一个表
输入:第一个表:res6

Material   item               quantity  ordnum
     101     91                 4         2
     101     92                 6         5
     101     93                 4         4
     102     97                 5         8
     103     98                 3         7

第二张table:res7

Date             item    ordnum
   2020-05-11        91       2
   2020-05-11        92       5
   2020-05-11        93       4
   2020-05-11        97       8
   2020-05-12        98       7

要求是我们需要考虑日期作为参考
2) 如果日期重复两次或n次,则输出应转到添加数量的第一项。
输出:

Material  item       date            quantity    ordnum
      101       91      2020-05-11           14        2
      102       97      2020-05-11            5        8
      103       98      2020-05-12            3        7

我使用了以下查询:

SELECT material, reqdate, SUM(quantity),
(
    SELECT item 
    FROM res6 in_tab1, res7 in_tab2
    WHERE in_tab1.material = out_tab1.material AND in_tab2.reqdate=out_tab2.reqdate
    LIMIT 1) AS item
FROM res6 out_tab1, res7 out_tab2
GROUP BY material, reqdate;

但数量没有增加。。请帮忙

gr8qqesn

gr8qqesn1#

尝试下面的脚本
你可以在这里查看演示

SELECT Material,Date,
MIN (res6.item) Itemm,
SUM(quantity) quantity,
MIN(res6.ordnum) ordnum 
FROM res6
INNER JOIN res7
ON res7.ordnum = res6.ordnum 
AND res6.item = res7.item 
AND Date IS NOT NULL
GROUP BY Material,Date

根据您的评论更新了下面的脚本-
演示2在这里

SELECT B.Material,
(SELECT item FROM res6 WHERE Material = B.Material AND ordnum = MIN(A.ordnum)) item,
A.DATE,
(SELECT SUM(quantity)  FROM res6 WHERE Material = B.Material) quantity,
MIN(A.ordnum) ordnum
FROM res7 A
INNER JOIN res6 B ON A.item = B.item AND A.ordnum = B.ordnum
GROUP BY B.Material,A.DATE

根据您的意见进行最终查询。只是缺少对连接条件的定义
演示3

SELECT material, reqdate, 
SUM(quantity), 
( 
    SELECT in_tab1.item 
    FROM res6 in_tab1, res7 in_tab2 
    WHERE in_tab1.material = out_tab1.material 
    AND in_tab2.reqdate=out_tab2.reqdate LIMIT 1
) AS item 
FROM res6 out_tab1
-- Converted Joining as standard practice  
INNER JOIN res7 out_tab2
ON out_tab1.item = out_tab2.item  -- Missing
AND out_tab1.ordnum = out_tab2.ordnum  -- Missing
GROUP BY material, reqdate
bvhaajcl

bvhaajcl2#

试试这个
选择res7.date,res7.item from res7 innerjoin res6 on res6.item=res7.item order by res7.date[asc/desc]

相关问题