[英]SQL Derived Table / Formula
SQL 2005: SQL 2005:
I am working on set of SQL queries which generate a formula.我正在研究一组生成公式的 SQL 查询。
This Mathematical calculation, Example: (3000 -30)/1477*100 = 201.1 % has to be generated from set of Tables.此数学计算,例如:(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
I guess you are looking for something like this?我猜你正在寻找这样的东西?
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
Hmm, I think I'd try something more along these lines:嗯,我想我会在这些方面尝试更多:
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
Please note that I do not have an SQL server instance to test this against.请注意,我没有 SQL 服务器实例来对此进行测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.