문제

I am looking for the cleanest, shortest, simplest, and most efficient way to do this using T-SQL. I hope that a single way is all of those things, but I realize that it may not be.

I have tried (unsuccessfully) using PIVOT, but what I think I need is to PIVOT by chunks AND without aggregating

I queried a large table to obtain this result: (the result is ordered by year by the Number descending. the Number is the Number of occurrences of people born with that Name in the given year)

Name    Number  Year
John    9655    1880
William 9532    1880
James   5927    1880
Charles 5348    1880
George  5126    1880
John    8769    1881
William 8524    1881
Charles 5442    1881
George  4664    1881
James   4636    1881
John    9557    1882
James   9298    1882
William 5892    1882
George  5193    1882
Charles 5092    1882

I want to turn the above result into this:

1880    1881    1882
John    John    John
William William James
James   Charles William
Charles George  George
George  James   Charles
도움이 되었습니까?

해결책

You can use PIVOT to get the result, the only thing that you will need to do is add a row_number() that is generated by partitioning the data by year ordered by the number. This unique sequence then allows you to return multiple rows for each year when you apply the aggregate function. Also since you want to convert string data you need to use either the max or min aggregate function:

select [1880], [1881], [1882]
from
(
  select name, year,
    row_number() over(partition by year
                      order by number desc) seq
  from yourtable
) d
pivot
(
  max(name)
  for year in ([1880], [1881], [1882])
) p;

See SQL Fiddle with Demo. Returns:

|    1880 |    1881 |    1882 |
|---------|---------|---------|
|    John |    John |    John |
| William | William |   James |
|   James | Charles | William |
| Charles |  George |  George |
|  George |   James | Charles |
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top