大家好,我有桌子,上面有产品和价格。我所要做的就是显示每种产品的最低价格,如果它没有出现在价格表中,则显示价格为null的产品这是我写的一个查询
SELECT
t15_catalogue_line.T15_GROUP, sc_products.product_code,sc_products.unic,
sc_products.name_ru, UPPER(TRIM(sc_products.brief_description_ru)) AS
brief_description_ru, sc_products.suupplier, price.Price,
sc_group_discounts.`action`, sc_group_discounts.procent,
sc_products.productID, price.in_stock, price.supplier, t10_item.T10_ITEM,
t10_item.unic, t10_item.T10_DESC, t10_item.T10_IMG, t10_item.T10_ITEM_GROUP,
t10_item.T10_FIELD1, t10_item.T10_FIELD2, t10_item.T10_FIELD3,
t10_item.T10_FIELD4, t10_item.T10_FIELD5, t10_item.T10_FIELD6,
t10_item.T10_FIELD7, t10_item.T10_FIELD8, t10_item.T10_FIELD9,
t10_item.T10_FIELD10, t10_item.T10_FIELD11, t14_item_fields.T14_ITEM_GROUP,
t14_item_fields.T14_FIELD, t14_item_fields.T14_NAME,
t14_item_fields.T14_UNIT, t14_item_fields.T14_SEARCH
FROM sc_products
LEFT OUTER JOIN t15_catalogue_line ON (sc_products.unic = t15_catalogue_line.unic)
LEFT OUTER JOIN price ON (sc_products.product_code = price.item) AND (sc_products.suupplier = price.postavchik)
LEFT OUTER JOIN sc_group_discounts ON (sc_products.item_group = sc_group_discounts.item_group)
LEFT OUTER JOIN t10_item ON (sc_products.unic = t10_item.unic and sc_products.CatText=t10_item.CatText)
LEFT OUTER JOIN t14_item_fields ON (t10_item.T10_ITEM_GROUP = t14_item_fields.T14_ITEM_GROUP)
WHERE sc_products.CatText = 'bearing'
AND t15_catalogue_line.T15_CARTYPE = '42769'
AND t15_catalogue_line.T15_GROUP = '546678' and sc_products.unic is not null and sc_products. unic!='' and
CASE WHEN price.Price is null then price.Price is null else price.Price=(SELECT
MIN(price.Price) from price where price.unic=sc_products.unic
AND price.CatText='bearing') end
GROUP BY sc_products.unic
ORDER by isnull (price.Price),price.Price ASC
现在它只显示那些价格为null的其他声明并不起作用。
答案 0 :(得分:0)
在case
中,您必须使用THEN NULL
,而不是THEN price.Price IS NULL
:
AND CASE
WHEN price.Price IS NULL THEN NULL
ELSE
(
SELECT
MIN(price.Price)
FROM
price
WHERE
price.unic = sc_products.unic
AND price.CatText = 'bearing'
)
END
您应使用AND
条件,而不是结束案例,如下所示:
AND ( ( price.CatText = 'bearing' AND price.unic = sc_products.unic)
OR ( price.CatText = 'bearing' AND price.unic is numm) )
并最终选择min(your_value)应该在select子句中,而不是在where中。
答案 1 :(得分:0)
另一个答案很接近......你可能需要通过额外的LEFT-JOIN来做到这一点,你的ELSE子选择是......
LEFT JOIN ( 选择 price.unic, MIN(price.Price)为minprice 从 价钱 哪里 price.CatText ='承载' 通过...分组 price.unic)ByUnic ON sc_products.unic = ByUnic.unic
然后你的案例的INSTEAD /当WHERE子句时,删除它。更改字段选择属性,将价格从... price.price改为:
COALESCE( price.Price, ByUnic.minPrice ) as Price
这将首先返回price.price字段。如果为null,则返回左连接表的值ByUnic,minPrice结果如果它存在,否则仍为null。如果您想要在Price.Price之前的最低价格,只需交换字段顺序,如
COALESCE( ByUnic.minPrice, price.Price ) as Price