我有以下sql代码。我使用带有日期间隔的WHERE子句。我的问题是我只希望在select语句的特定部分使用日期间隔。
我想将WHERE子句DATE限制为我在QtyInPeriod和ProfitInPeriod上的select而不是所选的其他列(Lines.Item,Inventory.ItemAlternative,Inventory.OnHandPhys,Inventory.Allocated,Inventorry.CostPrice,Brand& StockStatus)
我是否需要在2个单独的sql查询中获取数据,还是可以将WHERE DATE子句限制为select语句的一部分?
SELECT lines.Item,
Inventory.ItemAlternative,
Inventory.OnHandPhys,
Inventory.Allocated,
Inventory.CostPrice,
SUM(lines.Invoiced)*-1 AS QtySoldInPeriod,
(SUM(lines.AmountBase-lines.CostAmount))*-1 AS ProfitInPeriod,
replace(vInventoryOptional2Values.Value, '/', '') AS Brand,
Inventory.Optional3 AS StockStatus
FROM lines
INNER JOIN inventory ON lines.item = Inventory.item
INNER JOIN vInventoryOptional2Values ON Inventory.Optional2 = vInventoryOptional2Values.RecordID
WHERE Inventory.Item = 'ITEM#'
AND Lines.Date >= 'DATE'
AND Lines.Date <= 'DATE'
AND lines.Invoiced < 0
AND Inventory.Status = 0
AND Inventory.Optional3 <> 3
GROUP BY Lines.Item,
Inventory.Optional3,
Inventory.ItemAlternative,
Inventory.OnHandPhys,
Inventory.CostPrice,
vInventoryOptional2Values.Value,
Inventory.Allocated
HAVING SUM(lines.AmountBase-lines.CostAmount) < 0
编辑: 我尝试使用子查询,但无法使其工作:
SELECT lines.Item,
Inventory.ItemAlternative,
Inventory.OnHandPhys,
Inventory.Allocated,
Inventory.CostPrice,
replace(vInventoryOptional2Values.Value, '/', '') AS Brand,
Inventory.Optional3 AS StockStatus
(SELECT SUM(lines.Invoiced)*-1 AS QtySoldInPeriod
FROM (lines.item
WHERE Lines.Date >= '2014-01-01'
AND Lines.Date <= '2014-01-31' ) )
FROM lines
INNER JOIN inventory ON lines.item = Inventory.item
INNER JOIN vInventoryOptional2Values ON Inventory.Optional2 = vInventoryOptional2Values.RecordID
WHERE Inventory.Item = 'a158wa'
AND lines.Invoiced < 0
AND Inventory.Status = 0
AND Inventory.Optional3 <> 3
GROUP BY Lines.Item,
Inventory.Optional3,
Inventory.ItemAlternative,
Inventory.OnHandPhys,
Inventory.CostPrice,
vInventoryOptional2Values.Value,
Inventory.Allocated
答案 0 :(得分:0)
你不能。形式上,查询返回一组行,WHERE子句作为过滤器应用于行集。也就是说,它是被过滤的行集,而不是特定的列。
考虑使用Union运算符组合两个select语句。
答案 1 :(得分:0)
您应该使用子查询,并在更新的问题中,您的语法错误, 尝试使用,
SELECT lines.Item,
Inventory.ItemAlternative,
Inventory.OnHandPhys,
Inventory.Allocated,
Inventory.CostPrice,
replace(vInventoryOptional2Values.Value, '/', '') AS Brand,
Inventory.Optional3 AS StockStatus,
(SELECT SUM(l.Invoiced) * -1
FROM lines l
WHERE l.Date >= '2014-01-01'
AND l.Date <= '2014-01-31'
AND l.Item = lines.Item) AS QtySoldInPeriod
FROM lines
INNER JOIN inventory ON lines.item = Inventory.item
INNER JOIN vInventoryOptional2Values ON Inventory.Optional2 = vInventoryOptional2Values.RecordID
WHERE Inventory.Item = 'a158wa'
AND lines.Invoiced < 0
AND Inventory.Status = 0
AND Inventory.Optional3 <> 3
GROUP BY Lines.Item,
Inventory.Optional3,
Inventory.ItemAlternative,
Inventory.OnHandPhys,
Inventory.CostPrice,
vInventoryOptional2Values.Value,
Inventory.Allocated