如何对列进行求和;临时表的行?

时间:2014-08-08 08:40:50

标签: sql-server

我正在尝试总结列和&临时表的行。

SELECT 
D_U_C.MSLINK,
D_U_C.ItemNo,

CASE WHEN D_U_C.CondHDBolts like 'RED' THEN L_CSC1.Cost*D_U_C.HDBoltsLEN ELSE 0 END HDBolts,
CASE WHEN D_U_C.CondGrout = 'RED' THEN L_CSC2.Cost*D_U_C.Grout_V_lt ELSE 0 END Grout,
CASE WHEN D_U_C.CondPlinth = 'RED' THEN L_CSC3.Cost*D_U_C.Plinth_V_cubM ELSE 0 END Plinth,
CASE WHEN D_U_C.CondBase = 'RED' THEN L_CSC4.Cost*D_U_C.Base_V_cubM ELSE 0 END Base

into #temp

FROM D_UG_CONC D_U_C
LEFT JOIN L_ConcSupportCosts L_CSC1
ON L_CSC1.Item = 'Grout'
LEFT JOIN L_ConcSupportCosts L_CSC2
ON L_CSC2.Item = 'HDBolts'
LEFT JOIN L_ConcSupportCosts L_CSC3
ON L_CSC3.Item = 'PlinthConc'
LEFT JOIN L_ConcSupportCosts L_CSC4
ON L_CSC4.Item = 'BaseConc'

Where ItemNo like '0D3-PS-02_%'

select *
from #temp
order by ItemNo

SELECT SUM([HDBolts]+[Grout]+[Plinth]+[Base] )as 'ItemCost'

FROM   #Temp

SELECT SUM([HDBolts])as 'HDBolts',
   SUM([Grout])as 'Grout',
   SUM([Plinth])as 'PlinthConc',
   SUM([Base])as 'BaseConc'

FROM   #Temp  

DROP TABLE #temp;
GO

结果

MSLINK  ItemNo       HDBolts    Grout       Plinth      Base        
89619   0D3-PS-10_1  50.0000    0.0000000   0.0000000   39.2000000
89620   0D3-PS-10_2  00.0000    50.0000000  10.0000000  0.0000000
-----------------------------------------------------------------------------
ItemCost
194.02
----------------------------------------------------------------------------

HDBolts Grout         Plinth       Base
50.0000 50.0000000    10.0000000   39.2000000

----------------------------------------------------------------------------

必填结果

MSLINK  ItemNo       HDBolts    Grout         Plinth      Base         ItemCost
89619   0D3-PS-10_1  50.0000    0.0000000     0.0000000   39.2000000   89.2000000
89620   0D3-PS-10_2  00.0000    50.0000000    10.0000000   0.0000000   60.0000000 
                               TotalCost  149.2000000
--------------------------------------------------------------------------------------
HDBolts Grout         Plinth       Base
50.0000 50.0000000    10.0000000   39.2000000

1 个答案:

答案 0 :(得分:1)

将您的查询修改为以下内容:

查询1

SELECT *, [HDBolts]+[Grout]+[Plinth]+[Base] as 'ItemCost'
FROM   TempTable

Demo Sql Fiddle

<强>产地:

| MSLINK |      ITEMNO | HDBOLTS | GROUT | PLINTH | BASE | ITEMCOST |
|--------|-------------|---------|-------|--------|------|----------|
|  89619 | 0D3-PS-10_1 |      50 |     0 |      0 | 39.2 |     89.2 |
|  89620 | 0D3-PS-10_2 |       0 |    50 |     10 |    0 |       60 |

查询2

SELECT SUM([HDBolts]+[Grout]+[Plinth]+[Base])as 'ItemCost'
FROM   TempTable    

Demo Sql Fiddle

<强>产地:

| ITEMCOST |
|----------|
|    149.2 |

查询3

SELECT SUM([HDBolts])as 'HDBolts',
   SUM([Grout])as 'Grout',
   SUM([Plinth])as 'PlinthConc',
   SUM([Base])as 'BaseConc'
FROM   TempTable 

Demo Sql Fiddle

<强>产地:

| HDBOLTS | GROUT | PLINTHCONC | BASECONC |
|---------|-------|------------|----------|
|      50 |    50 |         10 |     39.2 |