我正在使用Sqlite数据库项目开发C#WPF。
对于Sqlite数据库,我有3个Tablels。如下:
名称:
id -INTEGER
name -TEXT
表1:
nameID -INTEGER
amnt1 -INTEGER
amnt2 -REAL
amnt3 -INTEGER
amnt4 -INTEGER
amnt5 -INTEGER
amnt6 -INTEGER
entryDate -TEXT
表2:
id -INTEGER
nameID -INTEGER
amnt1 -INTEGER
amnt2 -INTEGER
amnt3 -INTEGER
amnt4 -INTEGER
amnt5 -INTEGER
amnt6 -INTEGER
location -INTEGER
entryDate -TEXT
首先,我想用sum()函数对表1'所有列进行求和,如:
select sum(amnt1),sum(amnt2),sum(amnt3),sum(amnt4),sum(amnt5),sum(amnt6)
from Table1
where entryDate between '2018-05-01' and '2018-05-20'
和table2 Sum:
select sum(amnt1),sum(amnt2),sum(amnt3),sum(amnt4),sum(amnt5),sum(amnt6)
from Table2
where entryDate between '2018-05-01' and '2018-05-20'
现在我要做的是再次总结Table1和Table2的所有匹配列。我试过像:
select sum(Table1.amnt1)+sum(Table2.amnt1),(Table1.amnt2)+sum(Table2.amnt2),sum(Table1.amnt3)+sum(Table2.amnt3),sum(Table1.amnt4)+sum(Table2.amnt4),sum(Table1.amnt5)+sum(Table2.amnt5),sum(Table1.amnt6)+sum(Table2.amnt6)
from Table1
join Table2 On Table1.nameID=Table2.nameID
where Table1.entryDate between '2018-05-01' and '2018-05-20'
也许我的查询不正确,因此我得不到正确的结果!什么是解决方案而不使查询看起来很难看?
哦,我尝试使用SQL Fiddle,但有时它不起作用,仍然是链接:http://sqlfiddle.com/#!5/9eecb7
如果sqlfilldle不起作用,我已创建表并插入数据如下:
CREATE TABLE `Name` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` INTEGER );
insert into `Name` VALUES(1,'test1');
insert into `Name` VALUES(2,'test2');
CREATE TABLE "Table1" ( `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, `nameID` INTEGER, `amnt1` INTEGER, `amnt2` INTEGER, `amnt3` INTEGER, `amnt4` INTEGER, `amnt5` INTEGER, `amnt6` INTEGER, `entryDate` TEXT );
INSERT INTO Table1 VALUES(NULL,1,1,1,1,1,1,1,'2018-04-01');
INSERT INTO Table1 VALUES(NULL,2,1,1,1,1,1,1,'2018-05-01');
INSERT INTO Table1 VALUES(NULL,1,1,1,1,1,1,1,'2018-05-06');
CREATE TABLE "Table2" ( `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, `nameID` INTEGER, `amnt1` INTEGER, `amnt2` INTEGER, `amnt3` INTEGER, `amnt4` INTEGER, `amnt5` INTEGER, `amnt6` INTEGER, `entryDate` TEXT );
INSERT INTO Table2 VALUES(NULL,1,1,1,1,1,1,1,'2018-04-02');
INSERT INTO Table2 VALUES(NULL,1,1,1,1,1,1,1,'2018-05-05');
INSERT INTO Table2 VALUES(NULL,2,1,1,1,1,1,1,'2018-05-06');
答案 0 :(得分:1)
我相信你需要使用UNION ALL
:
SELECT sum(amnt1),sum(amnt2),sum(amnt3),sum(amnt4),sum(amnt5),sum(amnt6)
FROM (select amnt1,amnt2,amnt3,amnt4,amnt5,amnt6
FROM Table1
where entryDate between '2018-05-01' and '2018-05-20'
UNION ALL
select amnt1,amnt2,amnt3,amnt4,amnt5,amnt6
FROM Table2
where entryDate between '2018-05-01' and '2018-05-20') sub
<强> SQLFiddle Demo 强>