总和然后分组?

时间:2015-10-22 19:33:52

标签: sql

无法弄清楚如何制定这个公式,然后按年获得答案。

Select
((Select Sum(#FinancialView2.CONVERTED_AMOUNT)*-1
FROM   #FinancialView2
WHERE  #FinancialView2."SECTION_NUMBER"=300 
AND #FinancialView2.BU_CODE in ('10','11','W0')
GROUP BY FinancialYear) 
+
(Select Sum(#FinancialView2.CONVERTED_AMOUNT)*-1
FROM   #FinancialView2
WHERE  #FinancialView2."SECTION_NUMBER"=400 
AND #FinancialView2.BU_CODE in ('10','11','W0')
AND #FinancialView2.DeptCode not in ('403','413')))
/
((Select Sum(#FinancialView2.CONVERTED_AMOUNT)*-1
FROM   #FinancialView2
WHERE  #FinancialView2."LINE_NUMBER"=110 
AND #FinancialView2.BU_CODE in ('10','11','W0')) 
+
(Select Sum(#FinancialView2.CONVERTED_AMOUNT)*-1
FROM   #FinancialView2
WHERE  #FinancialView2."LINE_NUMBER"=115 
AND #FinancialView2.BU_CODE in ('10','11','W0'))
+
(Select Sum(#FinancialView2.CONVERTED_AMOUNT)*-1
FROM   #FinancialView2
WHERE  #FinancialView2."LINE_NUMBER"=120
AND #FinancialView2.BU_CODE in ('10','11','W0')) 
+
(Select ISNULL(Sum(#FinancialView2.CONVERTED_AMOUNT)*-1,0)
FROM   #FinancialView2
WHERE  #FinancialView2."LINE_NUMBER"=125
AND #FinancialView2.BU_CODE in ('10','11','W0')))*-1

我试过' Group By'在这里,但由于显而易见的原因,它不会工作

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

Loks喜欢你需要一些条件聚合(如果我正确翻译了条件,请仔细检查):

Select FinancialYear,
 (
   Sum(CASE WHEN #FinancialView2."SECTION_NUMBER"=300
            THEN #FinancialView2.CONVERTED_AMOUNT ELSE 0 END)*-1
+  Sum(CASE WHEN #FinancialView2."SECTION_NUMBER"=400 AND #FinancialView2.DeptCode not in ('403','413')
            THEN #FinancialView2.CONVERTED_AMOUNT ELSE 0 END)*-1
  )
/
 (
   Sum(CASE WHEN #FinancialView2."SECTION_NUMBER"=110
            THEN #FinancialView2.CONVERTED_AMOUNT ELSE 0 END)*-1
+  Sum(CASE WHEN #FinancialView2."SECTION_NUMBER"=115
            THEN #FinancialView2.CONVERTED_AMOUNT ELSE 0 END)*-1
+  Sum(CASE WHEN #FinancialView2."SECTION_NUMBER"=120
            THEN #FinancialView2.CONVERTED_AMOUNT ELSE 0 END)*-1
+  Sum(CASE WHEN #FinancialView2."SECTION_NUMBER"=125
            THEN #FinancialView2.CONVERTED_AMOUNT ELSE 0 END)*-1
 )
WHERE #FinancialView2.BU_CODE in ('10','11','W0')
GROUP BY FinancialYear

这可以进一步简化为:

Select FinancialYear,
 (
   Sum(CASE WHEN #FinancialView2."SECTION_NUMBER"=300
              OR (#FinancialView2."SECTION_NUMBER"=400 AND #FinancialView2.DeptCode not in ('403','413'))
            THEN #FinancialView2.CONVERTED_AMOUNT ELSE 0 END)*-1
 )
/
 (
   Sum(CASE WHEN #FinancialView2."SECTION_NUMBER" IN (110, 115, 120, 125)
            THEN #FinancialView2.CONVERTED_AMOUNT ELSE 0 END)*-1
 )
WHERE #FinancialView2.BU_CODE in ('10','11','W0')
GROUP BY FinancialYear

最后,col*-1-col

完全相同