SQL Totals分组在一列中

时间:2012-02-10 23:38:52

标签: java sql sqlite

我有一个类似[MainTable]的SQLite表:

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

我希望得到一个像这样输出的查询:

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

我的问题是,如果我使用UNION ALL来获取总数,那么查询会多次查找[MainTable]。 我想在单个查找中计算所有总计,以使用SQLite查询而不是java代码来提高速度。

我只在SQLite中使用它,而不是在另一个引擎上。

1 个答案:

答案 0 :(得分:0)

使用Type,Total和Scrap列创建一个新表,然后使用单独的SQL语句插入所需的数据,如下所示:

第一步:使用以下列创建一个newTable :(类型,总计,废料)

第二步:运行以下语句:

INSERT INTO newTable 
SELECT "machine" as type, machine, sum(scrap) 
from yourFirstTable;

INSERT INTO newTable 
SELECT "product" as type, product, sum(scrap) 
from yourFirstTable;

或者如果您在一个查询中需要这些,您可以执行以下操作:

SELECT "machine" as type, machine, sum(scrap) 
from yourFirstTable
UNION
SELECT "product" as type, product, sum(scrap) 
from yourFirstTable

等...

你也可以多次加入同一张桌子并获得相同的结果:

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