三个查询的结果分别动态分为三个单独的列

时间:2015-06-12 11:22:06

标签: sql sql-server select sql-server-2014

我希望将这三个查询的结果分别动态分为三个单独的列。

SELECT SUM(fee_amt) as Total_Fee from FEEDTL where Semester_No='2015SM' AND Registration_No='2015-1234' AND Fee_type='TUITION FEE' 

SELECT SUM(fee_amt) as Balance from FEEDTL where Semester_no='2015SM' AND Registration_No='2015-1235' AND Fee_type='TUITION FEE' and Verify='No' 

SELECT SUM(fee_amt) as Paid_Amt from FEEDTL where Semester_no='2015SM' AND Registration_No='2015-1236' AND Fee_type='TUITION FEE' and Verify='Yes'

1 个答案:

答案 0 :(得分:1)

您可以将这些查询合并到一个查询中。 常见条件可以保留在where子句中,非常见条件可以移动到各自case内的sum表达式:

SELECT SUM(CASE registration_no WHEN '2015-1234' THEN fee_amt END) AS Total_Fee,
       SUM(CASE WHEN registration_no = '2015-1235' AND verify = 'No' 
                THEN fee_amt END) AS Balance,
       SUM(CASE WHEN registration_no = '2015-1236' AND verify = 'Yes 
                THEN fee_amt END) AS Pair_amt
FROM   feedtl
WHERE  semester_no = '2015SM' AND fee_type = 'TUITION FEE'

请注意,case表达式默认返回null(即,当whenelse子句不匹配时,sum表达式null忽略public class YourModelClass { private string _Name; public string Name { get { return _Name; } set { _Name = value; } } private string _LoginTime; public string LoginTime { get { return _LoginTime; } set { _LoginTime = value; } } } s。