如果存储过程混乱

时间:2014-08-14 07:46:25

标签: sql stored-procedures

这是一张表

name a  b  c   normal loan status
abc  50 60 70               normal
bcd  50 50 50               loan

我首先想要的是根据它们的状态获得列a,b和c的总值。状态正常的名称总数应该在正常列之下,状态贷款的总数应该在贷款栏下。

我应该得到abc的正常50 + 60 + 70 和bcd的贷款总额50 + 50 + 50

我该怎么做?

我在SP中试过了,但似乎无法得到它

2 个答案:

答案 0 :(得分:0)

我认为以下是您的需求。以下查询是标准ANSI查询:

SELECT    name
          ,SUM(CASE WHEN status = 'normal' THEN (a + b + c) ELSE 0 END)  AS normal
          ,SUM(CASE WHEN status = 'loan' THEN (a + b + c) ELSE 0 END)  AS loan
          ,status

FROM     yourTable

GROUP BY name, status

<强>输出:

name    normal  loan    status
bcd      0      150     loan
abc      180    0       normal

根据您在评论中的要求更新现有行:

UPDATE  yourTable
SET normal = CASE WHEN status = 'normal' THEN (a + b + c) ELSE 0 END,
loan = CASE WHEN status = 'loan' THEN (a + b + c) ELSE 0 END
FROM yourTable

请注意,每次插入新记录时都需要更新表格,或者更改原始INSERT语句以包含这些列。

答案 1 :(得分:0)

在单一选择中你可以做到。

尝试

SELECT *,(CASE WHEN [status]='normal' THEN [a]+[b]+[c] ELSE null END) as normal,(CASE WHEN [status]='loan' THEN [a]+[b]+[c] ELSE null END) as loan FROM YourTable