# Coordinates carry their aggregation depth; SQL NULL remains an ordinary axis value. class CountsPivotLayout def self.depths(keys, sorts, measures: true) return [] if keys.length < 2 || sorts.first&.first == 'count' || sorts.first&.first&.match?(/\Am[0-9]+\z/) relevant = sorts.map(&:first).select { keys.include?(_1) || (measures && (_1 == 'count' || _1.match?(/\Am[0-9]+\z/))) } order = (relevant + keys).uniq (1...keys.length).select { order.first(_1).sort == keys.first(_1).sort } end def self.headers(values, depths, next_values: nil, grand: false) result = [] values.each_with_index do |tuple, index| result << { values: tuple, kind: 'data' } following = values[index + 1] || next_values depths.reverse_each do |depth| prefix = tuple.first(depth) next if following && following.first(depth) == prefix result << { values: prefix, kind: 'subtotal' } end end result << { values: [], kind: 'grand_total' } if grand result end end