I'd like a way to summarise a database table so that rows sharing a common ID are summarised into one row of output.
My tools are SQLite and Python 2.x.
For example, given the following table of fruit prices at my local supermarkets...
+--------------------+--------------------+--------------------+
|Fruit |Shop |Price |
+--------------------+--------------------+--------------------+
|Apple |Coles |$1.50 |
|Apple |Woolworths |$1.60 |
|Apple |IGA |$1.70 |
|Banana |Coles |$0.50 |
|Banana |Woolworths |$0.60 |
|Banana |IGA |$0.70 |
|Cherry |Coles |$5.00 |
|Date |Coles |$2.00 |
|Date |Woolworths |$2.10 |
|Elderberry |IGA |$10.00 |
+--------------------+--------------------+--------------------+
... I want to produce a summary table showing me the price of each fruit at each supermarket. Blank spaces should be filled by NULLs.
+----------+----------+----------+----------+
|Fruit |Coles |Woolworths|IGA |
+----------+----------+----------+----------+
|Apple |$1.50 |$1.60 |$1.70 |
|Banana |$0.50 |$0.60 |$0.70 |
|Cherry |NULL |$5.00 |NULL |
|Date |$2.00 |$2.10 |NULL |
|Elderberry|NULL |NULL |$10.00 |
+----------+----------+----------+----------+
I believe the literature calls this a "pivot table" or a "pivot query", but apparently SQLite doesn't support PIVOT
. (The solution in that question uses hardcoded LEFT JOIN
s. This doesn't really appeal to me because I don't know the "column" names in advance.)
Right now I do this by iterating through the entire table in Python and accumulating a dict
of dicts
, which is a bit klutzy. I am open to better solutions, either in Python or SQLite, that will give the data in tabular form.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…