代码改变世界

SQL CASE WHEN ... THEN ... ELSE.. END 实例

2015-02-03 11:32  hf_sun  阅读(268)  评论(0编辑  收藏  举报

用一个SQL语句完成不同条件的分组(SELECT部分):

select QuoteOrderId,SUM(case when(ApprovalStatus=1)then Amount else 0 end) AS CloseAmount,SUM(case when(ApprovalStatus=2)then Amount else 0 end) AS ApprovalAmount from dbo.PurchaseSettleAccountsDetails a inner join dbo.PurchaseSettleAccounts b on a.PurchaseSettleAccountId=b.ID group by QuoteOrderId

已知数据按照另外一种方式进行分组SELECT部分):

SELECT
CASE WHEN salary <= 500 THEN '1'
WHEN salary > 500 AND salary <= 600  THEN '2'
WHEN salary > 600 AND salary <= 800  THEN '3'
WHEN salary > 800 AND salary <= 1000 THEN '4'
ELSE NULL END salary_class,
COUNT(*)
FROM    Table_A
GROUP BY
CASE WHEN salary <= 500 THEN '1'
WHEN salary > 500 AND salary <= 600  THEN '2'
WHEN salary > 600 AND salary <= 800  THEN '3'
WHEN salary > 800 AND salary <= 1000 THEN '4'
ELSE NULL END;