[英]stacking pairs of columns with ids from rows of data
嗨,我正在嘗試對產品及其屬性進行排序,但問題是屬性的標頭不是基於產品的名稱和描述。 所以我舉例說:
Product id | attribute 1 name | attribute 1 desc | attribute 2 name | attribute 2 desc
1001 | screen size | 15" | DCR | 10,000:1
1002 | DCR | 200,000:1 | Widescreen | yes
這一行繼續進行,直到該產品有許多屬性。
我需要的東西會吐出來:
Product id, attribute 1 name, attribute 1 desc
Product id, attribute 2 name, attribute 2 desc
所以它看起來像這樣:
1001, screen size, 15"
1001, DCR, 10,000:1
1002, DCR, 200,000:1
1002, widescreen, yes
有誰知道對這些信息進行排序的最佳方法是什么?
我一直在嘗試使用一些excel vba腳本,但我想知道是否有一種方法可以用ruby來實現它,因為這就是我現在正在學習的東西,這將是一個很好的真實世界的例子來深入研究ruby。
通過將屬性分離到自己的模型中,可以大大簡化此過程。
應用程序/模型/ product_attribute.rb
class ProductAttribute < ActiveRecord::Base
attr_accessible :name, :desc, :product_id
belongs_to :product
#...
end
應用程序/模型/ product.rb
class Product < ActiveRecord::Base
# ...
has_many :product_attributes
# ...
def self.sorted_attributes
Product.all.collect{|prod| prod.sorted_attributes}
end
def sorted_attributes
product_attributes.all(order: "name ASC").collect{|attr| [self.id, attr.name, attr]}
end
end
然后,您可以通過調用Product.sorted_attributes並編寫視圖代碼來顯示生成的2D數組,從而獲得所需的信息。
這是John Bustos在評論中提到的充實版本。
我正在處理這個示例數據( 這里是完整的工作簿 )
我們的想法是使用VBA循環遍歷列,並將它們輸出到一個很長的瘦表中。
Sub MakeSkinny()
Dim rng As Range
Dim clOutput As Range
Dim cl As Range
Set rng = Range("A3").CurrentRegion ' raw data'
Set clOutput = Range("A9") ' Where to output results'
Set cl = clOutput
' Add headers to the new table'
cl.Offset(0, 0).Value = "Item"
cl.Offset(0, 1).Value = "Attribute"
cl.Offset(0, 2).Value = "Value"
Set cl = cl.Offset(1, 0) ' go to the next row of output'
For i = 2 To rng.Rows.Count
iCol = 2 ' Start at column 2'
Do Until iCol >= 7 ' set to however many cols you have'
'Check for blank attribute name'
If rng.Cells(i, iCol) <> "" Then
cl.Offset(0, 0) = rng.Cells(i, 1) ' Item ID'
cl.Offset(0, 1) = rng.Cells(i, iCol) ' Attribute Name'
cl.Offset(0, 2) = rng.Cells(i, iCol + 1) ' Attribute Value'
Set cl = cl.Offset(1, 0) ' go to the next row of output'
End If
iCol = iCol + 2 'Advance to next set of attributes'
Loop
Next i
End Sub
希望有所幫助!
謝謝您的幫助。 我實際上已經知道了。 我只是對lineemup宏稍作調整
Sub lineemupSAS()
Dim i As Long
Dim dr As Long
For i = 2 To Cells(2, Columns.Count).End(xlToLeft).Column Step 2
dr = Cells(Rows.Count, 1).End(xlUp).Row + 1
Cells(2, 1).Resize(6500).Copy Cells(dr, 1)
Cells(2, i).Resize(6500).Copy Cells(dr, 2)
Cells(2, 1 + i).Resize(6500).Copy Cells(dr, 3)
Next i
End Sub
其中6500表示數據集中的行數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.