仅当不存在非空值的行时,才输出具有空值的行

时间:2020-02-09 18:03:04

标签: mysql

尽我所能提出我的问题...

我有一个包含历史数据的定价表。因此,每件商品都有特定日期的价格。困难之处在于,这些行还具有类型(1 =采购订单的价格,2 =销售订单)和VendorID。

可以在一行中填写VendorID:然后该行的价格用于该特定供应商。如果该表中没有任何具有VendorID的项目的行,但确实有VendorID为null的行,则该行应在结果中。

因此,如果结果中有两行,其中一行具有VendorID值,另一行具有VendorID为空,则具有该值的行应位于结果集中,而具有空值的行可能不在结果集中。结果集。

此外,结果集应仅包含最新的价格,因此我必须考虑“ FromDate”。

'VendorID'列的名称选择不佳,因为类型= 2的行用于销售订单,但是现在让我们忘记它;-)

enter image description here

如果我希望所有类型为1的项目都想要具有以下结果集:

ID | ItemID | FromDate   | Type | VendorID | price
------------------------------------------------
1  | 1.     | 2020-01-01 | 1    | 97       | 2.45
9  | 2      | 2020-02-15 | 1    | 97       | 3.88
7  | 3      | 2020-01-01 | 1    | 97       | 2.55

假设表中没有ID 3、4和9(因此,对于特定的VendorID 97,第2项没有定价),结果应为:

ID | ItemID | FromDate   | Type | VendorID | price
------------------------------------------------
1  | 1      | 2020-01-01 | 1    | 97       | 2.45
13 | 2      | 2020-01-01 | 1    | NULL     | 999.45
7  | 3      | 2020-01-01 | 1    | 97       | 2.55

对于ItemID 2,这意味着没有为VendorID 97设置特定价格,但有一个常规价格集(VendorID为空),现在应该将该价格放入结果集中。

我希望我现在能更清楚地解释它。...

我现在已经编写了很多查询,并且在Google上搜索了很多,但是我找不到如何使它执行我想要的操作。我尝试了独特的排序,但是没有运气。一定很简单,但我找不到。

到目前为止,我有以下Mysql查询,但是a)它输出VendorID为null且具有值的行两者; b)我认为它非常复杂,但无法弄清楚如何使其更简单,更快

SELECT I.ItemID, I.Name, b.vendorID, b.max_date, IP.Price, T.Percentage
FROM Items I

 JOIN
    (
      SELECT ItemID, VendorID, MAX(FromDate) max_date, type
      FROM ItemPrices
    WHERE 
    Type = 1 AND
    FromDate < '2020-02-30' AND
    VendorID = (SELECT ID FROM Vendors WHERE VendorID = 'V001') OR VendorID IS NULL
    GROUP BY ItemID, VendorID

     ) b ON I.ID = b.ItemID

JOIN ItemPrices IP ON IP.ItemID = b.ItemID AND IP.Type = b.type AND IP.FromDate = b.max_date AND (IP.VendorID = b.VendorID OR IP.VendorID IS NULL)

LEFT JOIN TaxCodes T ON T.ID =

(
  SELECT TC.TaxCodeID FROM TaxCombinations TC
  WHERE
  TC.Direction = 1 AND
  TC.TaxAreaID = (SELECT TaxArea FROM Vendors WHERE ID = (SELECT ID FROM Vendors WHERE VendorID = 'V001') )
  AND TC.ItemTaxID = I.ItemTaxID
)


ORDER BY I.ItemID ASC

还查看了以下网址,但仍然不知道该怎么做:
Distinct rows with non-null values taking precedence over nulls
Select the non-null value if exists else null, but always select the row

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

使用NOT EXISTS

select t.* from tablename t
where t.vendorid is not null
or not exists (
  select 1 from tablename
  where itemid = t.itemid and vendorid is not null
)

请参见demo