我有以下查询,它返回针对特定公司的供应商的采购订单总价值(我们的集团中有多家公司)。
我想使用poheader.orderdate
添加日期范围但由于我没有编写此查询,它比我习惯的稍微复杂一些,我不知道在哪里添加此子句。
非常感谢任何建议。
SELECT vendor.Vendorid AS 'ID',
vendor.name AS 'Name',
Total
FROM vendor LEFT JOIN
(
select sum (podetail.orderqty * podetail.unitcost) AS Total,
podetail.VendorNum,
podetail.Company
from podetail
where exists (
select 1
from poHeader
where poHeader.OrderNum = podetail.OrderNum
and poHeader.ApprovalStatus = 'A'
)
and exists (
select 1
from vendor
WHERE vendor.company = 'MyCompany'
and vendor.VendorNum = podetail.VendorNum
and vendor.Company = podetail.Company
)
group by podetail.VendorNum,
podetail.Company
) OD ON vendor.Vendornum = OD.Vendornum
and vendor.Company = OD.Company
WHERE vendor.company = 'MyCompany'
ORDER BY vendor.name
答案 0 :(得分:1)
好的,一旦格式化,它看起来并不那么可怕,现在呢?
现在你可以看到where子句放在哪里了?
像
这样的东西SELECT vendor.Vendorid AS 'ID',
vendor.name AS 'Name',
Total
FROM vendor LEFT JOIN
(
select sum (podetail.orderqty * podetail.unitcost) AS Total,
podetail.VendorNum,
podetail.Company
from podetail
where exists (
select 1
from poHeader
where poHeader.OrderNum = podetail.OrderNum
and poHeader.ApprovalStatus = 'A'
/*-------PLACE THE Date Range Check HERE------*/
AND poheader.orderdate BETWEEN @StartDate AND @EndDate
)
and exists (
select 1
from vendor
WHERE vendor.company = 'MyCompany'
and vendor.VendorNum = podetail.VendorNum
and vendor.Company = podetail.Company
)
group by podetail.VendorNum,
podetail.Company
) OD ON vendor.Vendornum = OD.Vendornum
and vendor.Company = OD.Company
WHERE vendor.company = 'MyCompany'
ORDER BY vendor.name
答案 1 :(得分:1)
我正在假设'添加日期范围'是什么意思。我假设您要过滤掉属于特定范围的结果:
SELECT vendor.Vendorid AS 'ID', vendor.name AS 'Name', Total
FROM vendor
LEFT JOIN (select sum (podetail.orderqty * podetail.unitcost) AS Total, podetail.VendorNum, podetail.Company
from podetail
where exists
(select 1
from poHeader
where poHeader.OrderNum = podetail.OrderNum and poHeader.ApprovalStatus = 'A')
/*this line*/ and convert(varchar(8),poHeader.orderdate,112) between '20100101' and '20101231'
and exists
(select 1 from vendor
WHERE vendor.company = 'MyCompany'
and vendor.VendorNum = podetail.VendorNum
and vendor.Company = podetail.Company)
group by podetail.VendorNum, podetail.Company) OD
ON vendor.Vendornum = OD.Vendornum
and vendor.Company = OD.Company
WHERE vendor.company = 'MyCompany'
ORDER BY vendor.name
为了便于阅读,我重新格式化了。
我也转换为varchar(8),但指定范围的参数可以是日期时间:
and poHeader.orderdate between getdate()-10 and getdate()
答案 2 :(得分:0)
看起来第一个存在子句应该修改如下:
(select 1 from poHeader where poHeader.OrderNum = podetail.OrderNum and poHeader.ApprovalStatus = 'A' and poheader.orderdate BETWEEN 'start_date' AND 'end_date's)