【问题标题】:Get exact rows when left join with another table与另一个表左连接时获取准确的行
【发布时间】:2016-04-05 11:26:29
【问题描述】:

我的查询是:

CREATE OR REPLACE VIEW saledetailfortax AS 
    SELECT
        sd.saledetaildate, sd.saledetailtime, sd.shopid, sd.productid,
        sd.unitid, sd.expdate, sd.batchno, sd.mrp, sd.totalprice, sd.qty, 
        sd.looseqty, ord.priceperunit as priceperunit, ord.taxid  
    FROM
        saledetail sd LEFT JOIN orvrcvdetailfortax ord
                                ON sd.productid = ord.productid
                                    AND sd.expdate = ord.expdate
                                    AND sd.batchno = ord.batchno
                                    AND sd.mrp = ord.mrp
    WHERE sd.saledetaildate <= '2016-03-31'
    ORDER BY  sd.saledetaildate , sd.saledetailtime;

在此处执行时,它返回的行数比执行此查询多:

SELECT
    sd.saledetaildate, sd.saledetailtime, sd.shopid,
    sd.productid,sd.unitid, sd.expdate, sd.batchno,
    sd.mrp, sd.totalprice, sd.qty, sd.looseqty
FROM saledetail sd
WHERE sd.saledetaildate <= '2016-03-31'
ORDER BY sd.saledetaildate, sd.saledetailtime;

我的目标是从saledetail 表中检索行并找出其对应的 priceperunit, taxid where productid, expdate, batchno, mrp 匹配。

问题在于相同的(productid, expdate, batchno, mrp) 不同的taxid 退出,因此记录不仅仅是欲望。如何减少它。

【问题讨论】:

  • 显而易见的答案是使用正确的 join 条件,这样您就有了 1-1 的匹配。这些是什么完全不清楚,因为您在问题中没有提供任何信息来帮助确定哪个匹配行是正确的。
  • 因为你的问题很模糊,所以我猜你可以尝试使用“GROUP BY”来删除重复的行。
  • 请不要使用GROUP BY(或DISTINCT)不了解为什么你有重复的行。
  • 正如@GordonLinoff 所说,请提供更多信息。表结构、样本数据、该样本数据的预期输出。一个很好的起点:stackoverflow.com/help/how-to-ask
  • @Tom H,由于具有相同 productid 、 expdate 、 batchno 、 mrp 的不同taxid 导致重复行

标签: sql postgresql join


【解决方案1】:
CREATE OR REPLACE VIEW saledetailfortax AS
    SELECT
        sd.saledetaildate, sd.saledetailtime, sd.shopid, sd.productid,
        sd.unitid, sd.expdate, sd.batchno, sd.mrp, sd.totalprice,
        sd.qty, sd.looseqty, ord.priceperunit as priceperunit, ord.taxid
    FROM saledetail sd LEFT JOIN orvrcvdetailfortax ord
                            ON sd.productid = ord.productid
    WHERE sd.saledetaildate <= '2016-03-31'
    ORDER BY sd.saledetaildate , sd.saledetailtime;

你只需要在上面的 on 之后写一个 2 条件

other 向我发送两个表的数据

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    • 2016-01-31
    • 2011-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多