I have a SQLite table like that [MainTable]:
Date | Machine | Product | Scrap
---------------------------------------
2012-02-06 | M1 | P1 | 100
2012-02-06 | M2 | P1 | 110
2012-02-06 | M2 | P2 | 200
2012-02-07 | M3 | P3 | 300
and I want to get a query that makes an output like that:
Type | Total | Scrap
------------------------------------
Machine | M1 | 100
Machine | M2 | 310
Machine | M3 | 300
Product | P1 | 210
Product | P2 | 200
Product | P3 | 300
Date | 2012-02-06 | 410
Date | 2012-02-07 | 300
Date-Machine | 2012-02-06 M2 | 310
My problem is that if I use UNION ALL to get the totals, the query lookup in to the [MainTable] a lot of times. I want to calculate all the totals in a single lookup to improve the speed using the SQLite query instead of the java code.
I need this only in SQLite, not on another engine.
Create a new table with the Type, Total and Scrap columns and then insert the data you need with separate SQL statements like this:
step one: create a newTable with these columns: (type, total, scrap)
step two: run these statements:
INSERT INTO newTable
SELECT "machine" as type, machine, sum(scrap)
from yourFirstTable;
INSERT INTO newTable
SELECT "product" as type, product, sum(scrap)
from yourFirstTable;
or if you need these all in one query you could do something like this:
SELECT "machine" as type, machine, sum(scrap)
from yourFirstTable
UNION
SELECT "product" as type, product, sum(scrap)
from yourFirstTable
etc...
You can also join multiple times to same table and get same result like this:
SELECT TYPE, ITEM, sum(scrap) as sumTot
FROM (SELECT "machine" as type, machine as item, scrap from yourFirstTable) as A,
(SELECT "machine" as type, product as item, scrap) as B
GROUP BY TYPE, ITEM
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.