日期:2014-05-18  浏览次数:20582 次

交叉表在加一点难度~(解决马上给分)
表是如下格式
name   object   score
a           EN           89
a           CH           78
a           HO           99
b           EN           34
b           CH           88
b           HO           66
要求生成下面样式
我想在多个字段做总合应该怎样处理
name   EN   CH   HO   Sum
a         89   78   99   累加
b         34   88   66   累加

------解决方案--------------------
CTRL+V就行了,没难度~~~

Create Table A
(
[date] Varchar(10),
[quarter] Varchar(10),
[value] Numeric(10,1)
)
GO

Insert A Select '2006-7-29 ', 'Q1 ',0.2
Union All Select '2006-7-29 ', 'Q2 ',0.5
Union All Select '2006-7-29 ', 'Q3 ',0.3
Union All Select '2006-7-30 ', 'Q1 ',0.1
Union All Select '2006-7-30 ', 'Q2 ',0.2
Union All Select '2006-7-30 ', 'Q3 ',0.7
select * from a
GO

Declare @S Varchar(8000)
Set @S= ' '
Select @S=@S + ',SUM(Case [quarter] When ' ' ' + [quarter] + ' ' ' Then value Else 0 End) As ' + [quarter]
From A Group By [quarter] Order By [quarter]
Select @S= 'Select [date] ' + @S + ' ,SUM(value) As total From A Group By [date] Order By [date] '
EXEC(@S)
GO

Drop Table A
------解决方案--------------------
还有更面熟的呢


下面的语句用于创建 Pivot 表并在其中填入第一个表中的数据:

USE Northwind
GO

CREATE TABLE Pivot
( Year SMALLINT,
Quarter TINYINT,
Amount DECIMAL(2,1) )
GO
INSERT INTO Pivot VALUES (1990, 1, 1.1)
INSERT INTO Pivot VALUES (1990, 2, 1.2)
INSERT INTO Pivot VALUES (1990, 3, 1.3)
INSERT INTO Pivot VALUES (1990, 4, 1.4)
INSERT INTO Pivot VALUES (1991, 1, 2.1)
INSERT INTO Pivot VALUES (1991, 2, 2.2)
INSERT INTO Pivot VALUES (1991, 3, 2.3)
INSERT INTO Pivot VALUES (1991, 4, 2.4)
GO

下面是用于创建旋转结果的 SELECT 语句:

SELECT Year,
SUM(CASE Quarter WHEN 1 THEN Amount ELSE 0 END) AS Q1,
SUM(CASE Quarter WHEN 2 THEN Amount ELSE 0 END) AS Q2,
SUM(CASE Quarter WHEN 3 THEN Amount ELSE 0 END) AS Q3,
SUM(CASE Quarter WHEN 4 THEN Amount ELSE 0 END) AS Q4
FROM Northwind.dbo.Pivot
GROUP BY Year
GO

该 SELECT 语句还处理其中每个季度占多行的表。GROUP BY 语句将 Pivot 中一年的所有行合并成一行输出。当执行分组操作时,SUM 聚合中的 CASE 函数的应用方式是这样的:将每季度的 Amount 值添加到结果集的适当列中,在其它季度的结果集列中添加 0。

如果该 SELECT 语句的结果用作电子表格的输入,那么电子表格将很容易计算每年的合计。当从应用程序使用 SELECT 时,可能更易于增强 SELECT 语句来计算每年的合计。例如:

SELECT P1.*, (P1.Q1 + P1.Q2 + P1.Q3 + P1.Q4) AS YearTotal
FROM (SELECT Year,
SUM(CASE P.Quarter WHEN 1 THEN P.Amount ELSE 0 END) AS Q1,
SUM(CASE P.Quarter WHEN 2 THEN P.Amount ELSE 0 END) AS Q2,
SUM(CASE P.Quarter WHEN 3 THEN P.Amount ELSE 0 END) AS Q3,
SUM(CASE P.Quarter WHEN 4 THEN P.Amount ELSE 0 END) AS Q4
FROM Pivot AS P
GROUP BY P.Year) AS P1
GO


------解决方案--------------------
declare @t table(name varchar(10),object varchar(10),score int)
insert into @t selec