我正在编写查询以生成药物清单及其平均价格。
我的表格如下:
CREATE TABLE [dbo].[drugPurchases](
[importId] [bigint] IDENTITY(1,1) NOT NULL,
[importDate] [datetime] NOT NULL,
[rxNumber] [float] NULL,
[accountNumber] [nvarchar](255) NULL,
[lastName] [nvarchar](255) NULL,
[firstName] [nvarchar](255) NULL,
[dob] [datetime] NULL,
[ssn] [nvarchar](10) NULL,
[drugName] [nvarchar](255) NULL,
[drugStrength] [nvarchar](255) NULL,
[dosage] [nvarchar](255) NULL,
[quantityDispensed] [float] NULL,
[price] [float] NULL,
[facilityCode] [nvarchar](255) NULL,
[fillDate] [datetime] NULL,
[processed] [bit] NOT NULL
特定药物的一些样本数据称为“ENALAPRIL”。
select
drugName,
drugStrength,
dosage,
quantityDispensed,
price
from
drugPurchases
where
drugName = 'ENALAPRIL'
and drugStrength = '10MG'
and fillDate >= Dateadd(Month, Datediff(Month, 0, DATEADD(m, -6, current_timestamp)), 0)
结果:
ENALAPRIL 10MG TAB 60 1.14
ENALAPRIL 10MG TAB 60 7.79
ENALAPRIL 10MG TAB 60 7.79
ENALAPRIL 10MG TAB 60 7.79
ENALAPRIL 10MG TAB 180 3.42
ENALAPRIL 10MG TAB 120 2.28
ENALAPRIL 10MG TAB 240 31.18
ENALAPRIL 10MG TAB 300 38.97
ENALAPRIL 10MG TAB 240 31.18
ENALAPRIL 10MG TAB 60 7.79
ENALAPRIL 10MG TAB 60 7.79
ENALAPRIL 10MG TAB 60 7.79
ENALAPRIL 10MG TAB 60 7.79
ENALAPRIL 10MG TAB 120 15.59
ENALAPRIL 10MG TAB 120 15.59
ENALAPRIL 10MG TAB 60 7.79
ENALAPRIL 10MG TAB 60 1.14
ENALAPRIL 10MG TAB 60 1.14
ENALAPRIL 10MG TAB 60 1.14
ENALAPRIL 10MG TAB 60 1.14
ENALAPRIL 10MG TAB 60 1.14
ENALAPRIL 10MG TAB 60 7.79
ENALAPRIL 10MG TAB 60 7.79
ENALAPRIL 10MG TAB 180 3.42
我的目标是获得每种力量的ENALAPRIL的平均价格。我的疑问是:
SELECT
distinct(drugName),
drugStrength,
dosage,
ROUND(price / quantityDispensed, 2) as 'calc'
FROM
drugPurchases
where
fillDate >= Dateadd(Month, Datediff(Month, 0, DATEADD(m, -6, current_timestamp)), 0)
and drugName = 'ENALAPRIL'
and drugStrength = '10MG'
GROUP BY
drugName,
drugStrength,
dosage,
(price / quantityDispensed)
ORDER BY
drugName,
drugStrength
但我的结果集为ENALAPRIL 10MG产生了两种不同的价格:
ENALAPRIL 10MG TAB 0.02
ENALAPRIL 10MG TAB 0.13
知道为什么会这样做以及我可能需要调整查询吗?
答案 0 :(得分:2)
看起来它是在您的小组中通过药物购买中的两个单独条目进行分组...
(price / quantityDispensed)
您可以使用SUM(price / quantityDispensed)聚合这两个值并删除该组。
SELECT
drugName,
drugStrength,
dosage,
ROUND(
Avg(price / quantityDispensed), 2) as 'calc'
FROM
drugPurchases
where
fillDate >= Dateadd(Month, Datediff(Month, 0, DATEADD(m, -6, current_timestamp)), 0)
and drugName = 'ENALAPRIL'
and drugStrength = '10MG'
GROUP BY
drugName,
drugStrength,
dosage,
ORDER BY
drugName,
drugStrength
答案 1 :(得分:1)
您按价格/数量进行分组,因此每个价格/数量结果都会产生一个单独的行返回。在价格/数量中使用汇总并将其从组中删除。我希望这有相同的结果:
SELECT
distinct(drugName),
drugStrength,
dosage,
ROUND(avg(price / quantityDispensed), 2) as 'calc'
FROM
drugPurchases
where
fillDate >= Dateadd(Month, Datediff(Month, 0, DATEADD(m, -6, current_timestamp)), 0)
and drugName = 'ENALAPRIL'
and drugStrength = '10MG'
GROUP BY
drugName,
drugStrength,
dosage
ORDER BY
drugName,
drugStrength