我需要父母编号加上孩子的数目,孩子加上其孩子的数目,依此类推

时间:2019-07-10 07:30:10

标签: sql sql-server tsql

我的表有两列accountCode,allocationBudget

!(https://drive.google.com/open?id=1kaGlpar7tyKmqUSqrLEgVIdz4LLzQt3c

我想做的是每个父母在他的分配领域中,它的孩子的总分配,对于孩子来说,也将在它的分配领域中,它的孩子的总分配,所以最后一个孩子得到仅分配

    @IBAction func btnActionSignOut(_ sender: UIButton) {

        let alertController = UIAlertController(title: AppSettings.shared.appName, message: "Are you sure you want to logout?", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "Yes", style: .default) { (action:UIAlertAction) in
            // Clear access tokens and logout user.
            UserDefaults.standard.setValue(nil, forKeyPath: "accessToken")
            UserDefaults.standard.setValue(nil, forKeyPath: "refreshToken")
            UserDefaults.standard.setValue(nil, forKeyPath: "idToken")

            _ = SessionController.shared.logout()
            self.dismiss(animated: true, completion: nil)
        }
        let noAction = UIAlertAction(title: "No", style: .default) { (action:UIAlertAction) in
            // Do nothing. Alert dismissed.
        }
        alertController.addAction(okAction)
        alertController.addAction(noAction)
        self.present(alertController, animated: true, completion: nil)
    }

所需结果如下: !(https://drive.google.com/open?id=1mUDLWFQU9bYsuD4IhMyxExxeyaDOzWSL

我希望这是可以理解的,并且我已经能够将其传达给您。 预先谢谢你

2 个答案:

答案 0 :(得分:1)

您可以使用自我加入。

select
    T1.accountCode,
    SUM(T2.allocationBudget) as allocationBudget
from T1
left join T1 as T2 on SUBSTRING(T2.accountCode,1,LEN(T1.accountCode)) = T1.accountCode
group by T1.accountCode

答案 1 :(得分:1)

如果我假设您的AcountCode中的前7位数字是父ID,则以下脚本应能提供预期的结果。

SELECT A.AcountCode,
CASE 
    WHEN B.AcountCode IS NOT NULL THEN B.Total 
    ELSE A.AllocationBudget 
END AllocationBudget
FROM your_table A
LEFT JOIN (
    SELECT 
    LEFT(CAST(AcountCode AS VARCHAR(MAX)),7) AcountCode,
    SUM(AllocationBudget) Total 
    FROM your_table 
    GROUP BY LEFT(CAST(AcountCode AS VARCHAR(MAX)),7)
)B ON A.AcountCode = B.AcountCode