【发布时间】:2016-05-18 21:57:32
【问题描述】:
我是一个新的 SAS/SQL 用户,我有一个数据集,我需要将一些行转换为列。我认为有一种更快或更简单的方法可以做到这一点,我想给大家一些建议。我的示例将更好地解释我的问题:
这是我拥有的数据集:
Month ID Car Claim_Type Cost_of_claim
1 1243 Ferrari Collision 12,000
2 6437 Peugeot Fire 50,000
5 0184 Citroen Stole 3,000
9 1930 Fiat Medical 1,000
3 2934 GM Liability 20,000
我需要创建一个这样的数据集:
Month ID Car Collision Fire Stole Medical Liability
1 1243 Ferrari 12,000 0 0 0 0
2 6437 Peugeot 0 50,000 0 0 0
5 0184 Citroen 0 0 3,000 0 0
9 1930 Fiat 0 0 0 1,000 0
3 2934 GM 0 0 0 0 20,000
我只是将一些行转换为列...
我正在考虑做类似的事情来创建我的新数据集:
proc sql;
select Month, ID, CAR
case when Claim_Type = 'Collision' then Cost_of_claim end Collision,
case when Claim_Type = 'Fire' then Cost_of_claim end Fire,
case when Claim_Type = 'Stole' then Cost_of_claim end Stole,
case when Claim_Type = 'Medical' then Cost_of_claim end Medical,
case when Claim_Type = 'Liability' then Cost_of_claim end Liability
from my_table;
问题是数据量很大,我认为这种方式可能效率不高。此外,在我的数据集中,我有更多的列和行,并且不想在case when 语句中输入所有可能性,因为维护代码似乎并不容易(或用户友好)。
有人可以帮我解决这个问题吗?
【问题讨论】: