我想交换列的值以对它们进行排序。
表:
if(CONDITION TO REMOVE) {
print("deleting function...")
df <- df[-c(df[,'Num2']),]
}
结果应该是:
pid | category1 | category2 | category3
----+-----------+-----------+----------
1 | a | b |
2 | b | a |
3 | a | c | b
我的方法是选择行到列,按组排序并返回新列:
pid | category1 | category2 | category3
----+-----------+-----------+----------
1 | a | b |
2 | a | b |
3 | a | b | c
我找到了枢轴功能,但在这种情况下并没有真正理解如何使用它。
答案 0 :(得分:1)
Sean Lange对于如何纠正数据库架构是正确的。
在此之前,您可以通过以下方式获取结果:
使用cross apply(values ...)
将您的数据与row_number()
一同取消,以便在common table expression内重新排序category
;然后使用条件聚合重新编译该数据:
;with cte as (
select
t.pid
, u.category
, rn = row_number() over (partition by t.pid order by u.category)
from t
cross apply (values (category1),(category2),(category3)) u(category)
where nullif(u.category,'') is not null
)
select
pid
, category1 = max(case when rn = 1 then category end)
, category2 = max(case when rn = 2 then category end)
, category3 = max(case when rn = 3 then category end)
from cte
group by pid
rextester演示:http://rextester.com/GIG22558
返回:
+-----+-----------+-----------+-----------+
| pid | category1 | category2 | category3 |
+-----+-----------+-----------+-----------+
| 1 | a | b | NULL |
| 2 | a | b | NULL |
| 3 | a | b | c |
+-----+-----------+-----------+-----------+
答案 1 :(得分:0)
您可以按以下方式进行转动
class Dog : Animal {
private (set) var limbs: Int = 4
private (set) var weight: Int = 50 // Error: Setter for property 'weight' must be declared internal because it matches a requirement in internal protocol 'Animal'
}
输出如下:
select * from (
select *, RowN = row_number() over(partition by pid order by Category) from Categories
) a
pivot (max(category) for RowN in ([1],[2],[3])) p
对于动态列列表,您可以使用如下:
+-----+-----------+-----------+-----------+
| Pid | Category1 | Category2 | Category3 |
+-----+-----------+-----------+-----------+
| 1 | a | b | NULL |
| 2 | a | b | NULL |
| 3 | a | b | c |
+-----+-----------+-----------+-----------+