问题
I realise it is possible to create a crosstab within sqlite, but is it possible to dynamically determine the relevant categories/columns at runtime rather than hardcoding them?
Given the following example, it can get rather tedious ...
SELECT
shop_id,
sum(CASE WHEN product = 'Fiesta' THEN units END) as Fiesta,
sum(CASE WHEN product = 'Focus' THEN units END) as Focus,
sum(CASE WHEN product = 'Puma' THEN units END) as Puma,
sum(units) AS total
FROM sales
GROUP BY shop_id
I managed to do this in SQLServer in a stored proceedure before and wondered if there was anything equivalent.
回答1:
No, you can't do that in SQLite, since analytic means in SQLite lack many usefull features available in heavier RDBMSes. Here is the corresponding ticket, but it is in the pending status.
回答2:
Old question, but anyway: I faked something like this in Ruby on Rails. For my purposes it works well.
def self.yearstats(attr)
# Determine number of columns
minyear = self.select("strftime('%Y', min(recorded_at)) AS minyear").first.minyear.to_i
maxyear = self.select("strftime('%Y', max(recorded_at)) AS maxyear").first.maxyear.to_i
# Stitch SQL query. Use explicit same column name to not confuse Rails' typecasting.
select_str = ["strftime('#{minyear}/%m/%d %H:%m', recorded_at) AS recorded_at"]
(minyear..maxyear).to_a.each do |y|
# avg because the table might have multiple rows per day
select_str += ["avg(case when strftime('%Y', recorded_at)='#{y}' then #{attr} end) AS value#{y}"]
end
self.select(select_str.join(",")).group("strftime('%m/%d', recorded_at)").all.collect {|row|
[row.recorded_at.utc.to_i*1000] + (minyear..maxyear).to_a.collect { |y| row.send("value#{y}") }
}
end
Note that for the first column I used a (fake) date using a fixed first year so that my graphing routines get a "real" date, not just day/month display. This is a little dirty but it works for my purposes. (Improvements still welcome...)
Instead of getting minyear and maxyear, you might want to do a SELECT DISTINCT.. to get the unique list of categories and modify the code appropriately.
来源:https://stackoverflow.com/questions/2921070/dynamically-create-categories-for-sqlite-pivot-crosstab