原文 http://www.gyurcit.hu/pivot.html

Dynamic Pivot table wizard

This stored procedure generate dynamic crosstable with multiple pivot columns by 4+1 parameters.

1. P_Row_Field Name of field that reperesent the spreadsheet's rows
2. P_Column_Field Name of field that store the name of columns
3. P_Value Name of field that represent the spreedsheet's value
4. P_From Name of source table
5. P_Where Filter expression (optional)

Values of second parameter field should not include apastrophe.  Procedure does not check paramaters (you must do that), so it may causes sql injection attack.

To source code click one of them

 
-- =================================================
-- Pivot Table Wizard (c) 2009 by GyurcIT
-- http://www.gyurcit.hu e-mail: gyurcit@gmail.com
-- ================================================= IF EXISTS (SELECT name FROM sysobjects
WHERE name = N'PivotWizard' AND type = 'P')
DROP PROCEDURE PivotWizard
GO
-----------------------------------------------------
-----------------------------------------------------
CREATE PROCEDURE PivotWizard
@P_Row_Field VARCHAR(255),
@P_Column_Field VARCHAR(255),
@P_Value VARCHAR(255),
@P_From VARCHAR(4000),
@P_Where VARCHAR(4000) = '1=1'
AS DECLARE @SQL NVARCHAR(4000) -- Build SQL statment that upload @Columns string
  -- with @P_Column_Filed values
CREATE TABLE #TEMP (ColumnField varchar(100))
SET @sql ='SELECT DISTINCT '+@P_Column_Field+' AS ColumnField'+
' FROM '+@P_From+
' WHERE '+@P_Where+
' ORDER BY '+@P_Column_Field
INSERT INTO #TEMP
EXEC(@sql)
PRINT @sql -- Check count of columns
DECLARE @Count_Columns int
SELECT @Count_Columns = COUNT(*) FROM #Temp
IF (@Count_Columns<1) OR (@Count_Columns>255) BEGIN
DROP TABLE #Temp
RAISERROR('%d is invalid columns amount. Valid is 1-255',
16,1,@Count_columns)
RETURN
END
-- Upload @Columns from #Temp
DECLARE @Columns VARCHAR(8000),
@Column_Field VARCHAR(8000) SET @Columns = ''
DECLARE Column_cursor CURSOR LOCAL FOR
SELECT CAST(ColumnField AS VARCHAR(60))
FROM #Temp
OPEN Column_cursor
FETCH NEXT FROM Column_cursor
INTO @Column_Field
WHILE @@FETCH_STATUS = 0 BEGIN
SET @Columns = @Columns +
' SUM('+
' CASE WHEN '+@P_Column_Field+'='''+ @Column_Field+''''+
' THEN '+@P_Value+
' ELSE 0 END'+
') AS ['+ @Column_Field +'], '
FETCH NEXT FROM Column_cursor
INTO @Column_Field
END
CLOSE Column_cursor
DEALLOCATE Column_cursor
DROP TABLE #Temp IF @Columns='' RETURN 1
SET @Columns = Left(@Columns,Len(@Columns)-1) -- Build Pivot SQL statment
DECLARE @Pivot_SQL VARCHAR(8000)
SET @Pivot_SQL = 'SELECT ' +@P_Row_Field+', '+@Columns
SET @Pivot_SQL = @Pivot_SQL +' FROM ' +@P_From
SET @Pivot_SQL = @Pivot_SQL +' WHERE ' +@P_Where
SET @Pivot_SQL = @Pivot_SQL +' GROUP BY '+@P_Row_Field
SET @Pivot_SQL = @Pivot_SQL +' ORDER BY '+@P_Row_Field
SET @Pivot_SQL = @Pivot_SQL + '#' IF Right(@Pivot_SQL,1)<>'#'
BEGIN
RAISERROR('SQL statement is too long. It must be less
                than 8000 charachter!',16,1)
RETURN 1
END
SET @Pivot_SQL = Left(@Pivot_SQL,Len(@Pivot_SQL)-1) -- PRINT @Pivot_SQL
EXEC(@Pivot_SQL) RETURN 0
GO -- Example use Northwind database --
-- Example 1 --
exec PivotWizard 'ShipCountry',
'YEAR(OrderDate)*100+Month(OrderDate)',
'[ExtendedPrice]',
'dbo.Invoices',
'OrderDate BETWEEN ''1996/01/01'' and ''1996/12/31''' GO -- Example 2 --
exec PivotWizard 'ProductName',
'ShipCountry',
'[ExtendedPrice]',
'dbo.Invoices',
'OrderDate BETWEEN ''1996/01/01'' and ''1996/12/31'''
-- =================================================
-- Pivot Table Wizard MySQL (c) 2009 by GyurcIT
-- http://www.gyurcit.hu e-mail: gyurcit@gmail.com
-- =================================================
-- USE Database
DROP PROCEDURE IF EXISTS pivotwizard; CREATE DEFINER = 'root'@'192.168.1.119'
PROCEDURE pivotwizard(
IN P_Row_Field VARCHAR(255),
IN P_Column_Field VARCHAR(255),
IN P_Value VARCHAR(255),
IN P_From VARCHAR(4000),
IN P_Where VARCHAR(4000))
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE M_Count_Columns int DEFAULT 0;
DECLARE M_Column_Field varchar(60);
DECLARE M_Columns VARCHAR(8000) DEFAULT '';
DECLARE M_sqltext VARCHAR(8000);
DECLARE M_stmt VARCHAR(8000);
DECLARE cur1 CURSOR FOR SELECT CAST(Column_Field AS CHAR) FROM Temp;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; DROP TABLE IF EXISTS Temp;
SET @M_sqltext = CONCAT('CREATE TEMPORARY TABLE Temp ',
' SELECT DISTINCT ',P_Column_Field,
				' AS Column_Field',
' FROM ',P_From,
' WHERE ',P_Where,
' ORDER BY ', P_Column_Field); PREPARE M_stmt FROM @M_sqltext;
EXECUTE M_stmt; SELECT COUNT(*) INTO M_Count_Columns
 FROM Temp 
 WHERE Column_Field IS NOT NULL;

 IF (M_Count_Columns > 0) THEN
OPEN cur1;
REPEAT
FETCH cur1 INTO M_Column_Field;
IF (NOT done) and (M_Column_Field IS NOT NULL) THEN
SET M_Columns = CONCAT(M_Columns,
' SUM( CASE WHEN ',P_Column_Field,'=''',M_Column_Field,'''',
' THEN ',P_Value,
' ELSE 0 END) AS `', M_Column_Field ,'`,'); END IF;
UNTIL done END REPEAT;
    SET M_Columns = Left(M_Columns,Length(M_Columns)-1);
SET @M_sqltext = CONCAT('SELECT ',P_Row_Field,',',M_Columns,
' FROM ', P_From,
' WHERE ', P_Where,
' GROUP BY ', P_Row_Field,
' ORDER BY ', P_Row_Field); PREPARE M_stmt FROM @M_sqltext;
EXECUTE M_stmt;
END IF;
END
-- Example:
CALL pivotwizard('article','Month(date)',
'netto',
'invoice',
'(year(date)=2009)')

 

Dynamic Pivot table wizard SQL Server的更多相关文章

  1. Microsoft: Get started with Dynamic Data Masking in SQL Server 2016 and Azure SQL

    Dynamic Data Masking (DDM) is a new security feature in Microsoft SQL Server 2016 and Azure SQL DB. ...

  2. How can I list all foreign keys referencing a given table in SQL Server?

    How can I list all foreign keys referencing a given table in SQL Server?  how to check if columns in ...

  3. [转]How can I list all foreign keys referencing a given table in SQL Server?

    本文转自:https://stackoverflow.com/questions/483193/how-can-i-list-all-foreign-keys-referencing-a-given- ...

  4. SQL Server里PIVOT运算符的”红颜祸水“

    在今天的文章里我想讨论下SQL Server里一个特别的T-SQL语言结构——自SQL Server 2005引入的PIVOT运算符.我经常引用这个与语言结构是SQL Server里最危险的一个——很 ...

  5. SQL Server ->> 深入探讨SQL Server 2016新特性之 --- Temporal Table(历史表)

    原文:SQL Server ->> 深入探讨SQL Server 2016新特性之 --- Temporal Table(历史表) 作为SQL Server 2016(CTP3.x)的另一 ...

  6. Sql Server中的表访问方式Table Scan, Index Scan, Index Seek

    1.oracle中的表访问方式 在oracle中有表访问方式的说法,访问表中的数据主要通过三种方式进行访问: 全表扫描(full table scan),直接访问数据页,查找满足条件的数据 通过row ...

  7. 转:Sql Server中的表访问方式Table Scan, Index Scan, Index Seek

    0.参考文献 Table Scan, Index Scan, Index Seek SQL SERVER – Index Seek vs. Index Scan – Diffefence and Us ...

  8. Microsoft SQL Server Version List [sqlserver 7.0-------sql server 2016]

    http://sqlserverbuilds.blogspot.jp/   What version of SQL Server do I have? This unofficial build ch ...

  9. Microsoft SQL Server Version List(SQL Server 版本)

    原帖地址 What version of SQL Server do I have? This unofficial build chart lists all of the known Servic ...

随机推荐

  1. Xamarin.Android开发实践(四)

    原文:Xamarin.Android开发实践(四) Xamarin.Android下获取与解析JSON 一.新建项目 1.新建一个Android项目,并命名为为NetJsonList 2.右击引用,选 ...

  2. Nginx Rewrite规则初探(转)

    Nginx  rewrite(nginx url地址重写)Rewrite 主要的功能就是实现URL的重写,Nginx的Rewrite规则采用Pcre,perl兼容正则表达式的语法规则匹配,如果需要Ng ...

  3. More Divisors(反素数)

    More Divisors Time Limit: 2 Seconds      Memory Limit: 65536 KB Everybody knows that we use decimal ...

  4. Surround the Trees(凸包求周长)

    Surround the Trees Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Other ...

  5. 杭电 HDU 1242 Rescue

    http://acm.hdu.edu.cn/showproblem.php?pid=1242 问题:牢房里有墙(#),警卫(x)和道路( . ),天使被关在牢房里位置为a,你的位置在r处,杀死一个警卫 ...

  6. ios inHouse 公布应用

    一.明白几个概念 1.企业版IDP: 即iOS Development Enterprise Program.注意是$299/Year那种.并非$99/Year的那种 2.In House:是指企业内 ...

  7. linux命令sysctl使用

    以前没有注意过这个命令,直到有次在单位安装greenplum的时候,在没有配置系统参数的情况下,出现了设备空间不足的报错信息. 当然,安装的不是我的本机,而是公用的服务器,编辑修改系统参数后,仍然出现 ...

  8. 一个开源Delphi分类组件推荐网页

    https://github.com/Fr0sT-Brutal/awesome-delphi

  9. Dreamweaver显示花括号匹配

    按Ctrl+' 可以显示对应括号内的代码.dreamweaver没办法高亮显示花括号.而且没有块选择功能.个人认为Dreamweaver的编辑功能很糟糕.

  10. JavaScript自调用匿名函数

    Self-Invoking Anonymous Function,即自调用匿名函数.顾名思义,该函数没有名称,不同的是,该函数定义后立即被调用.该函数的作用是在应用中初始化或做一次性工作. 普通匿名函 ...