![](/img/trans.png)
[英]How can i read certain grouped attributes of objects from a .txt file and calculate their totals in Java?
[英]SQL Totals grouped in a single column
我有一个像[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中需要此功能,而在另一个引擎上则不需要。
使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.