如何比较SQL中的父子数据

时间:2013-02-19 17:01:17

标签: c# sql database sql-server-2008

我有两个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查询执行此操作。

抱歉我的英语不好。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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