首页 > 代码库 > SQL CASE WHEN ... THEN ... ELSE.. END 实例

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

用一个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部分):

SELECTCASE 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_AGROUP BYCASE 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;

 

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