SQL派生表/公式
SQL 2005: 我正在处理一组生成公式的SQL查询 这个数学计算,例如:(3000-30)/1477*100=201.1%,必须从一组表格中生成SQL派生表/公式,sql,sql-server,sql-server-2005,sql-server-2008,Sql,Sql Server,Sql Server 2005,Sql Server 2008,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
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
我猜你在找这样的东西
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
嗯,我想我应该在这方面多做些尝试:
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 server实例来测试这一点。您有代码,那么问题是什么呢?在这个patcustid=4797中,我将作为输入参数传递。我正在尝试在存储过程或用户定义函数中创建这组sql!!选择@TotalDaysSupply=sum(DaysSupply)作为[Total Days Supply]此语法引发异常!!您使用的最终公式(
totalDaysSupply-((daysSupply/daysBetween)*100)
)与所述公式(((totalDaysSupply-daysSupply)/daysBetween)*100
)不匹配。抱歉,我在没有management studio的情况下编写了此脚本。您的最终公式是[总供应天数]-[DaysSupply]/[DaysBetween]*100。我想它出了问题,但我猜你会弄明白的。