このクエリ:
; with numbered as
(
select *,
-- Assign number to each record
-- Numbering is separate for each pair of MLISNPI and CLIENT_ID1
-- Highest [Sum of desc] will get number 1 and so forth
Rank() over (partition by [MLISNPI]
order by [Sum of count] desc) rn
from [TargettingReport]
),
ctemain as (
select [MLISNPI],
[CLIENT_ID1],
[Sum of count]
from numbered
)
select * from ctemain
このサンプルデータを返しています:
+----------+------------+--------------+
| MLISNPI | CLIENT_ID1 | Sum of count |
+----------+------------+--------------+
| 03001363 | 101522 | 436 |
| 03001363 | 101596 | 0 |
| 03001363 | 101597 | 0 |
| 03002312 | 102165 | 66 |
| 03002742 | 100062 | 1 |
| 03002742 | 211074 | 1229 |
| 03006958 | 102235 | 21 |
| 03014986 | 213926 | 5 |
| 03016270 | 213143 | 3 |
| 03023284 | 212876 | 44 |
| 03023284 | 213801 | 55 |
| 03023821 | 100218 | 0 |
| 03028812 | 211144 | 133 |
| 03041666 | 100236 | 346 |
| 03041666 | 103164 | 65 |
| 03051731 | 213402 | 157 |
| 03058777 | 100572 | 28 |
| 03065509 | 101632 | 29 |
| 03071952 | 213632 | 6 |
| 03072059 | 101506 | 4 |
| 03081449 | 100087 | 398 |
| 03083205 | 214311 | 7 |
| 03117698 | 210178 | 203 |
| 03121302 | 214008 | 9 |
| 03139502 | 102179 | 1635 |
| 03147455 | 216022 | 21 |
| 03149204 | 211425 | 1 |
| 03186883 | 215748 | 1 |
| 03186883 | 215749 | 10 |
| 03190331 | 212289 | 26 |
| 03800285 | 101108 | 8052 |
| 03800285 | 101596 | 0 |
| 03800285 | 101597 | 0 |
| 03800350 | 212419 | 9 |
| 03800616 | 110461 | 0 |
| 03800616 | 213456 | 3 |
| 03802018 | 103136 | 32 |
| 03803412 | 201257 | 3 |
+----------+------------+--------------+
しかし、実際には、この PER のように水平方向にデータが必要ですMLISNPI
:
+----------+-----------+-------------+------------+-------------+-------------+----------+
| MLISNPI | clientid1 | sumofcount1 | clientid 2 | sumofcount2 | client id 3 | sum of 3 |
+----------+-----------+-------------+------------+-------------+-------------+----------+
| 03001363 | 101522 | 436 | 101596 | 0 | 101597 | 0 |
| 03002312 | 102165 | 66 | | | | |
| 03002742 | 100062 | 1 | 211074 | 1229 | | |
| 03006958 | 102235 | 21 | | | | |
| 03014986 | 213926 | 5 | | | | |
| 03016270 | 213143 | 3 | | | | |
| 03023284 | 212876 | 44 | 213801 | 55 | | |
+----------+-----------+-------------+------------+-------------+-------------+----------+
この形式のデータを取得するにはどうすればよいですか?
ここにテーブルの作成があります:
CREATE TABLE [dbo].[TargettingReport](
[MLISNPI] [varchar](50) NULL,
[IMS_PRESCRIBER_ID] [varchar](50) NULL,
[CLIENT_ID1] [varchar](50) NULL,
[Sum of count] [int] NULL
) ON [PRIMARY]