我有一张桌子:
+---------+--------------------+--------------------------+
| imd_id | Total TRx per Plan | plan name |
+---------+--------------------+--------------------------+
| 1111005 | 397.1556 | Medicaid Illinois (Idpa) |
| 1111005 | 25.7691 | Self Pay |
| 1111005 | 24.4355 | Tricare North Region |
| 1111005 | 15.0312 | 0 |
| 1111005 | 8.8425 | 0 |
| 1111005 | 8.3139 | 0 |
| 1111005 | 7.0534 | 0 |
| 1111005 | 6.2588 | 0 |
| 1111005 | 6.0358 | Bravo Health |
| 1111005 | 5.9872 | 0 |
| 1111531 | 133.9664 | Medicaid Al |
| 1111531 | 29.2318 | 0 |
| 1111531 | 23.2499 | 0 |
| 1111531 | 21.9774 | 0 |
| 1111531 | 14.9269 | 0 |
| 1111531 | 10.1903 | Self Pay |
| 1111531 | 5.4962 | 0 |
| 1111531 | 5.3409 | Bcbs Federal |
| 1111531 | 4.4801 | 0 |
| 1111531 | 3.8003 | 0 |
+---------+--------------------+--------------------------+
并尝试生成看起来像这样的数据
+---------+--------------------------+----------+---------------+-----------+----------------------+----------+
| imd_id | TopFirstPlan | TopFirst | TopSecondPlan | TopSecond | TopThirdPlan | TopThird |
+---------+--------------------------+----------+---------------+-----------+----------------------+----------+
| 1111005 | Medicaid Illinois (Idpa) | 0.78 | Self Pay | 0.05 | Tricare North Region | 0.04 |
| 1111531 | MEDICAID ALABAMA (AL) | 0.5 | Self Pay | 0.04 | Bcbs Federal | 0.02 |
+---------+--------------------------+----------+---------------+-----------+----------------------+----------+
请注意,创建 TOPFIRST、TOP SECOND、TOP THIRD 的方式是相应的Total TRx per Plan
除以该特定 IMD_ID 的计划总和。
到目前为止,我有这个:
select distinct a.imd_id,'topone'=
(select top 1 totalrxperplan
from book1 b
where b.imd_id = a.imd_id)/
(select SUM(totalrxperplan)
from book1 b
where b.imd_id = a.imd_id)
,'topplan2'=
(select top 1 xifinplanname
from book1 b
where b.imd_id = a.imd_id)
from book1 a
order by 1 asc
此查询将返回:
+---------+--------------------------+----------+
| imd_id | TopFirstPlan1 | TopFirst |
+---------+--------------------------+----------+
| 1111005 | Medicaid Illinois (Idpa) | 79% |
| 1111531 | MEDICAID ALABAMA (AL) | 53% |
+---------+--------------------------+----------+
但我需要添加其他列。
请注意,我们将ignore the plan name where it is 0