SQL Server - 分组到一列

时间:2017-03-29 06:12:44

标签: sql-server tsql

我现在对列有问题。我期望的结果假设是这样的:

EmployeeID    EducationalLoan
--------------
1             0.00
2             100.00

但结果显示,

EmployeeID    EducationalLoan
--------------
1             100.00
2             100.00

这次我想要实现的是,我想只看到员工贷款扣除价格,另一方面它只显示0.00。

我知道背后有一个小技巧,有人可以帮助我吗?

    DECLARE @EmployeeID AS INTEGER

SET @EmployeeID = 0;
SELECT DISTINCT
        [EmployeeID] = emp.EmployeeID,
        [EducationalLoan] = (SELECT ISNULL(SUM((CAST((lc.LoanAmount / ((dbo.fnNumberOfYears(CONVERT(VARCHAR(15), LoanDateStart, 101), CONVERT(VARCHAR(15), LoanPaymentDue, 101)) * 12)  * 2)) AS DECIMAL(18,2)))),0) FROM LoanContract lc WHERE lc.LoanTypeID = 1)
FROM Employee emp
    INNER JOIN Salary sal ON sal.EmployeeID = emp.EmployeeID
    INNER JOIN LoanContract lc ON lc.EmployeeID = emp.EmployeeID
    INNER JOIN LoanType lt ON lt.LoanTypeID = lc.LoanTypeID
    LEFT JOIN LoanPayments lp ON lp.LoanID = lc.LoanID
    LEFT JOIN LoanFrequency lf ON lf.LoanFrequencyID = lc.LoanFrequencyID
WHERE emp.EmployeeID IN (SELECT EmployeeID FROM Employee WHERE EmployeeID LIKE '%' + CASE WHEN ISNULL(@EmployeeID,0) <> 0 THEN CAST(ISNULL(@EmployeeID, 0) AS VARCHAR(15)) ELSE '' END + '%')
GROUP BY emp.EmployeeID, lt.LoanTypeID

1 个答案:

答案 0 :(得分:2)

您不在子查询中按员工过滤

ssk_known_hosts

应该是这样的:

    SELECT ISNULL(SUM((CAST((lc.LoanAmount / ((dbo.fnNumberOfYears(CONVERT(VARCHAR(15), LoanDateStart, 101), CONVERT(VARCHAR(15), LoanPaymentDue, 101)) * 12)  * 2)) AS DECIMAL(18,2)))),0) 
    FROM LoanContract lc 
    WHERE lc.LoanTypeID = 1