1

我有两个 SQL 表,如下所示

columns of T1: meterID, parentID, childID  
columns of T2: dataID, meterID, date, amount  

表格样本数据;

      T1                            T2
-------------              -------------------------
1 | null |  2  *           1 | 1 | 01,01,2013 | 100  *
1 | null |  3  *           2 | 2 | 01,01,2013 | 60   *
2 |   1  |  4              3 | 3 | 01,01,2013 | 40   *
2 |   1  |  5              4 | 4 | 01,01,2013 | 35
3 |   1  |  6              5 | 5 | 01,01,2013 | 25
3 |   1  |  7              6 | 6 | 01,01,2013 | 15
4 |   2  | null            7 | 7 | 01,01,2013 | 25
5 |   2  | null
6 |   3  | null  
7 |   3  | null  

我想比较孩子的金额总和是否等于父母的金额。

例如; meter1 是meter2 和meter3 的父级(带* 的行)。我想检查 100 = 60 + 40。
如何使用 SQL 查询来做到这一点。

对不起我的英语不好。

4

2 回答 2

1

此请求将子级分组并与父级进行比较。

SELECT t1.meterID, 
       CASE WHEN t1.amount = o.SumAmount THEN 'IsMatch' ELSE 'IsNotMatch' END
FROM T2 t1 OUTER APPLY (
                        SELECT SUM(t3.amount) AS SumAmount
                        FROM T1 t2 JOIN T2 t3 ON t2.childID = t3.meterID
                        WHERE t1.meterID = t2.meterID
                        GROUP BY t2.meterID
                        ) o

SQLFiddle上的演示

经过测试:您可以使用不带 GROUP BY 子句的查询

SELECT t1.meterID, 
       CASE WHEN t1.amount = o.SumAmount THEN 'IsMatch' ELSE 'IsNotMatch' END
FROM T2 t1 OUTER APPLY (
                        SELECT SUM(t3.amount) AS SumAmount
                        FROM T1 t2 JOIN T2 t3 ON t2.childID = t3.meterID
                        WHERE t1.meterID = t2.meterID
                        ) o
于 2013-02-19T17:19:08.953 回答
0

您想总结孩子的数量并与父母进行比较。这需要两个t2表连接,一个用于父级,一个用于子级。

以下查询假定t1没有重复的条目:

select t1.parentId, t1.childId,
       parent.amount as parent_amount,
       SUM(child.amount) as child_amount,
       (case when parent.amount = SUM(child.amount) then 'Match'
             else 'NoMatch'
        end)
from t1 left outer join
     t2 parent
     on t1.parentId = t2.meterid left outer join
     t3 child
     on t1.childId = t2.meterId
group by t1.parent_id, t1.childId, parent.amount
于 2013-02-19T17:05:49.110 回答