SQL 2005:
我正在处理一组生成公式的SQL查询。
这个数学计算,例如:(3000 -30)/ 1477 * 100 = 201.1%必须从一组表中生成。
Value : 3000 is generated from this query ..
select sum(DaysSupply) as [Total Days Supply] from vOeOrderWide where patcustid = 4797
Output is [Total Days Supply]
Value : 30 is generated from this query ..
select top 1 DaysSupply from VoeOrderwide where patcustid = 4797 order by datefilled desc
Output is [DaysSupply]
Value : 1477 is generated from these set of queries ...
declare @d1 datetime;
declare @d2 datetime;
set @d1= (select top 1 DateFilled from vOeOrderWide where patcustid = 4797
order by DateFilled asc)
set @d2= (select top 1 DateFilled from vOeOrderWide where patcustid = 4797 order by DateFilled DESC )
select DATEDIFF(d,@d1,@d2) as [Days Between]
Output is [Days Between]
I want to combine all these queries and generate the formula as ..
[Total Days Supply] - [DaysSupply] / [Days Between] * 100
答案 0 :(得分:1)
我猜你在找这样的东西?
DECLARE @TotalDaysSupply int, @DaysSupply int
select @TotalDaysSupply = sum(DaysSupply) as [Total Days Supply] from vOeOrderWide where patcustid = 4797
SET @DaysSupply = (select top 1 DaysSupply from VoeOrderwide where patcustid = 4797 order by datefilled desc)
declare @d1 datetime;
declare @d2 datetime;
DECLARE @DaysBetween int
set @d1= (select top 1 DateFilled from vOeOrderWide where patcustid = 4797
order by DateFilled asc)
set @d2= (select top 1 DateFilled from vOeOrderWide where patcustid = 4797 order by DateFilled DESC )
select @DaysBetween = DATEDIFF(d,@d1,@d2)
--[Total Days Supply] - [DaysSupply] / [Days Between] * 100
SELECT CAST(@TotalDaysSupply AS float) - @DaysSupply/ @DaysBetween * 100 AS Result
答案 1 :(得分:1)
WITH supply_data (Total_Days_Supply, Earliest_Date_Filled, Latest_Date_Filled) as (
SELECT SUM(DaysSupply), MIN(DateFilled), MAX(DateFilled)
FROM voeOrderWide
WHERE patCustId = 4797)
SELECT 100.00 * ((Total_Days_Supply - (SELECT TOP 1 DaysSupply
FROM voeOrderWide
WHERE patCustId = 4797
AND DateFilled = LatestDateFilled
ORDER BY DateFilled DESC))
/ DateDiff(d, Earliest_Date_Filled, Latest_Date_Filled))
FROM supply_data
请注意,我没有SQL服务器实例来测试它。