所以这就是......
我有两张桌子
表1:购买
id | aid | amount
1 1 5
2 3 8
3 7 2
4 1 3
表2:给定
id | aid | amount
1 2 4
2 1 3
3 7 5
4 1 1
我想要做的是通过援助字段将两个表和组的数量相加,但是在不同的行中。所以这两个表的结果将是:
结果
aid | sum1 | sum2
1 8 4
2 0 4
3 8 0
7 2 5
LINQ在VB.net中... 到目前为止我所拥有的是:
Dim one = From r In Purchase
Select r.aid, r.amount
Group By aid
Into total1 = Sum(amount)
Dim two = From p In Given
Select p.aid, p.amount
Group By aid
Into total2 = Sum(amount)
Dim final = From p In one
Join r In two On p.aid Equals r.aid
[ POPULATE LIST VIEW ]
For Each itm In final
Dim X As ListViewItem
X = lstPregledSaldo.Items.Add(itm.p.aid)
X.SubItems.Add(itm.p.total1)
X.SubItems.Add(itm.r.total2)
Next
但是这会产生我的左连接,如果有帮助的元素不在表格中,它不会在查询中使用它...我不知道如何解决这个问题:S
答案 0 :(得分:0)
虽然这不是您正在寻找的答案,但您可以使用Linqer或LINQpad将此SQL转换为LINQ。
WITH T AS (
SELECT P.aid
,SUM(P.amount) As 'tp'
,0 As 'tg'
FROM purchase P
GROUP BY P.aid
UNION
SELECT G.aid
,0
,SUM(G.amount)
FROM given g
GROUP BY g.aid
)
SELECT aid
,SUM(tp) AS 'Total Purchase'
,SUM(tg) As 'Total Given'
FROM T
GROUP BY aid
我还在SQL Fiddle上创建了一个测试环境。
答案 1 :(得分:0)
Dim Purchases = (From r In db.Purchase
Select r.aid, r.amount).ToList()
Dim Given = (From p In db.Given
Select p.aid, p.amount).ToList()
Dim aidValues = Purchases.Concat(Given).Select(Function(x) x.aid).OrderBy(Function(x) x).Distinct()
For Each a In aidValues
Dim sumP = Purchases.Where(Function(x) x.aid = a).Sum(Function(y) y.amount)
Dim sumG = Given.Where(Function(x) x.aid = a).Sum(Function(y) y.amount)
Console.WriteLine("aid {0}, sum1 {1}, sum2 {2}", a, sumP, sumG)
Next
您可以使用concat
从两个表格中选择所需的值(在这种情况下,列出不同的援助记录)。然后计算循环中每个表的总数。
结果:
aid 1, sum1 8, sum2 4
aid 2, sum1 0, sum2 4
aid 3, sum1 8, sum2 0
aid 7, sum1 2, sum2 5