我使用Postgres 9.1
来计算在给定时间段内使用为每位患者输入的发票的唯一患者就诊次数。
我有两列transactions.ptnumber
和transactions.dateofservice
,可以通过以下方式计算患者就诊次数:
select count(*)
from transactions
where transactions.dateofservice between '2012-01-01' and '2013-12-31'
问题在于,有时一名患者可能在同一天收到两张发票,但这应该算作只有一次患者就诊。
如果我在列SELECT DISTINCT
上使用GROUP BY
或transactions.ptnumber
,则会计算被看病人的数量(但不会是他们被看到的次数)。
如果我在SELECT DISTINCT
列上使用GROUP BY
或transactions.dateofservice
,则会计算有发票的天数。
不确定如何处理此事。
答案 0 :(得分:1)
这将每天返回独特的患者。
select count(distinct transactions.ptnumber) as cnt
from transactions
where transactions.dateofservice between '2012-01-01' and '2013-12-31'
group by transactions.dateofservice
你可以总结它们以获得整个时期的独特患者
select sum(cnt) from (
select count(distinct transactions.ptnumber) as cnt
from transactions
where transactions.dateofservice between '2012-01-01' and '2013-12-31'
group by transactions.dateofservice
)
答案 1 :(得分:0)
您可以使用子选择,考虑
Select count(*)
from (select ptnumber, dateofservice
from transactions
where dateofservice between '2012-01-01' and '2013-12-31'
group by ptnumber, dateofservice
)
您可能还希望将其设为存储过程,以便传入日期范围。
答案 2 :(得分:0)
有多种方法可以实现这一点,但您可以使用WITH
子句构建包含唯一访问的临时表,然后计算结果!
WITH UniqueVisits AS
(SELECT DISTINCT transactions.ptnumber, transactions.dateofservice
FROM transactions
WHERE transactions.dateofservice between '2012-01-01' and '2013-12-31')
SELECT COUNT(*) FROM UniqueVisits