日期:2014-05-17 浏览次数:20818 次
/* Orders 字段:goodsName(物品名) applyPerson(申请人) classify(物品类别) department(部门)totalPrice(总金额) */ CREATE TABLE OrderS(GoodsName NVARCHAR(20),ApplyPerson NVARCHAR(10),Classify NVARCHAR(20),Department NVARCHAR(10),TotalPrice DECIMAL(22,2)) INSERT INTO OrderS SELECT 'R0204301','01','A','SA',8102 UNION ALL SELECT 'R0204302','02','A','HR',12 UNION ALL SELECT 'R0204302','02','B','HR',21 UNION ALL SELECT 'R0204302','02','B','HR',1 DECLARE @Sql NVARCHAR(4000) SET @Sql =' ' SELECT @Sql =@Sql+'SUM(CASE WHEN Classify ='''+Classify+''' THEN TotalPrice ELSE 0 END) AS '+Classify+',' FROM OrderS GROUP BY Classify SET @Sql = 'SELECT Department,'+LEFT(@Sql,LEN(@Sql)-1)+' FROM OrderS GROUP BY Department' EXEC (@Sql) /* Department A B ---------- --------------------------------------- --------------------------------------- HR 12.00 22.00 SA 8102.00 0.00 (2 行受影响) */