I have a table:
+---------+--------------------+--------------------------+
| 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 |
+---------+--------------------+--------------------------+
and trying to generate data that looks like this
+---------+--------------------------+----------+---------------+-----------+----------------------+----------+
| 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 |
+---------+--------------------------+----------+---------------+-----------+----------------------+----------+
please note that the way the TOPFIRST, TOP SECOND, TOP THIRD are created is the corresponding Total TRx per Plan divided by the sum of the plans for that specific IMD_ID.
so far I have this:
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
this query will return:
+---------+--------------------------+----------+
| imd_id | TopFirstPlan1 | TopFirst |
+---------+--------------------------+----------+
| 1111005 | Medicaid Illinois (Idpa) | 79% |
| 1111531 | MEDICAID ALABAMA (AL) | 53% |
+---------+--------------------------+----------+
but I need to add on the other columns.
Please note that we will ignore the plan name where it is 0
Now the query:
If my assumption is right that the output numbers don’t match yours because you want to include even ‘0’ plans in the total, just not in the results, then you can just shift the where clause: