首先让我解释一下我不太使用SQL。
我正在使用其他人的代码,因此需要通过在WHERE
子句中将零打折掉来减少返回的行数。
但是我不确定该怎么做,因为我要折扣的商品是计算='openquantity'的结果
SELECT
stockallocations.partid,
stockallocations.quantity - issuedquantity as openquantity,
(CASE
WHEN stockallocations.source = 'SO' THEN stockallocations.reference
WHEN stockallocations.source = 'KIT' THEN stockallocations.worksorderid
ELSE 'Manual'
END) as source,
(CASE
WHEN stockallocations.source = 'SO' THEN salesorderitems.duedate
WHEN stockallocations.source = 'KIT' THEN worksorders.lateststartdate
ELSE 'createddate'
END) as needed
FROM
stockallocations
LEFT OUTER JOIN salesorderitems ON
stockallocations.orderid = salesorderitems.orderid AND
stockallocations.orderitemnumber = salesorderitems.itemnumber
LEFT OUTER JOIN worksorders ON
stockallocations.worksorderid = worksorders.id
WHERE
stockallocations.partid = 'ABC123'
--and openquantity > 0 (this doesn't work).
任何建议都将受到欢迎。
谢谢 标记
答案 0 :(得分:2)
尝试使用and (stockallocations.quantity - issuedquantity) > 0
代替and openquantity > 0
。别名在where
子句中无效。
答案 1 :(得分:0)
我不确定SQL是否允许您在WHERE子句中使用别名。
尝试以下方法:
WHERE
stockallocations.partid = 'ABC123'
AND stockallocations.quantity - issuedquantity > 0
谢谢, Dom
答案 2 :(得分:0)
您不能在WHERE
子句中使用别名。而是使用
SELECT * from (SELECT ...) WHERE openquantity > 0
或
WITH SEL1 as (SELECT ...)
SELECT * from SEL1 where openquantity > 0
或者如果计算是如此简单,只需将其复制:
SELECT ...
WHERE stockallocations.partid = 'ABC123'
AND stockallocations.quantity - issuedquantity > 0
请注意,前两个选项可能不适用于每个数据库。
答案 3 :(得分:0)
首先,我将使用表别名编写查询,并在WHERE
子句中解决列别名问题:
SELECT sa.partid, (sa.quantity - issuedquantity) as openquantity,
(CASE WHEN sa.source = 'SO' THEN sa.reference
WHEN sa.source = 'KIT' THEN sa.worksorderid
ELSE 'Manual'
END) as source,
(CASE WHEN sa.source = 'SO' THEN soi.duedate
WHEN sa.source = 'KIT' THEN wo.lateststartdate
ELSE 'createddate'
END) as needed
FROM stockallocations sa LEFT JOIN
salesorderitems soi ON
ON sa.orderid = soi.orderid AND
sa.orderitemnumber = soi.itemnumber LEFT JOIN
worksorders wo ON
ON sa.worksorderid = wo.id
WHERE sa.partid = 'ABC123' AND
sa.quantity > issuedquantity;
接下来,大概issuedquantity
来自stockallocations
。如果不是,则WHERE
子句将一个或多个LEFT JOIN
变成INNER JOIN
。
最后,CASE
表达式可疑。 ELSE
子句返回字符串,但是sa.worksorderid
可能是数字,并且日期看起来像日期。在单个表达式中混合这样的类型时,通常会遇到类型转换错误。