今天做东西的使用用到的一个区间统计,记录下来备忘下:
结果如下图:
数据来源:库=>AdventureWorks2008R2,表=> Sales.SalesOrderHeader[订单表],Sales.SalesOrderDetail[订单明细表]
统计订单数量及各个区间段的情况。
;WITH myCte AS ( select SalesOrderID,SUM(OrderQty*UnitPrice) amount from Sales.SalesOrderDetail GROUP BY SalesOrderID ) SELECT 条数= COUNT(1),序号,描述,N'占比'=CAST(COUNT(1)*100.0/总记录数 AS DECIMAL(10,4)) FROM ( SELECT 序号=1,ToStart=NULL,ToEnd=1000,描述='Bad' UNION ALL SELECT 序号=2,ToStart=1000,ToEnd=3000,描述='Normal' UNION ALL SELECT 序号=3,ToStart=3000,ToEnd=5000,描述='Good' UNION ALL SELECT 序号=4,ToStart=5000,ToEnd=NULL,描述='Excellent' ) a LEFT JOIN myCte b ON ((a.ToStart<=b.amount OR a.ToStart IS NULL ) ) AND (a.ToEnd>b.amount OR a.ToEnd IS NULL) CROSS JOIN (select 总记录数=COUNT(1) from Sales.SalesOrderHeader) c GROUP BY 序号,描述,总记录数