Home Database Mysql Tutorial SQL Server 动态行转列

SQL Server 动态行转列

Jun 07, 2016 pm 04:22 PM
server dynamic

一.本文所涉及的内容(Contents) 本文所涉及的内容(Contents) 背景(Contexts) 实现代码(SQL Codes) 方法一:使用拼接SQL,静态列字段; 方法二:使用拼接SQL,动态列字段; 方法三:使用PIVOT关系运算符,静态列字段; 方法四:使用PIVOT关系运算符,动态列字段;

   一.本文所涉及的内容(Contents)

  本文所涉及的内容(Contents)

  背景(Contexts)

  实现代码(SQL Codes)

  方法一:使用拼接SQL,静态列字段;

  方法二:使用拼接SQL,动态列字段;

  方法三:使用PIVOT关系运算符,静态列字段;

  方法四:使用PIVOT关系运算符,,动态列字段;

  二.背景(Contexts)

  其实行转列并不是一个什么新鲜的话题了,甚至已经被大家说到烂了,网上的很多例子多多少少都有些问题,所以我希望能让大家快速的看到执行的效果,所以在动态列的基础上再把表、分组字段、行转列字段、值这四个行转列固定需要的值变成真正意义的参数化,大家只需要根据自己的环境,设置参数值,马上就能看到效果了(可以直接跳转至:“参数化动态PIVOT行转列”查看具体的脚本代码)。行转列的效果图如图1所示:

SQL Server 动态行转列 三联

  (图1:行转列效果图)

  三.实现代码(SQL Codes)

  (一) 首先我们先创建一个测试表,往里面插入测试数据,返回表记录如图2所示:

  --创建测试表

  IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TestRows2Columns]') AND type in (N'U'))

  DROP TABLE [dbo].[TestRows2Columns]

  GO

  CREATE TABLE [dbo].[TestRows2Columns](

  [Id] [int] IDENTITY(1,1) NOT NULL,

  [UserName] [nvarchar](50) NULL,

  [Subject] [nvarchar](50) NULL,

  [Source] [numeric](18, 0) NULL

  ) ON [PRIMARY]

  GO

  --插入测试数据

  INSERT INTO [TestRows2Columns] ([UserName],[Subject],[Source])

  SELECT N'张三',N'语文',60 UNION ALL

  SELECT N'李四',N'数学',70 UNION ALL

  SELECT N'王五',N'英语',80 UNION ALL

  SELECT N'王五',N'数学',75 UNION ALL

  SELECT N'王五',N'语文',57 UNION ALL

  SELECT N'李四',N'语文',80 UNION ALL

  SELECT N'张三',N'英语',100

  GO

  SELECT * FROM [TestRows2Columns]

wps_clip_image-8842

  (图2:样本数据)

  (二) 先以静态的方式实现行转列,效果如图3所示:

  --1:静态拼接行转列

  SELECT [UserName],

  SUM(CASE [Subject] WHEN '数学' THEN [Source] ELSE 0 END) AS '[数学]',

  SUM(CASE [Subject] WHEN '英语' THEN [Source] ELSE 0 END) AS '[英语]',

  SUM(CASE [Subject] WHEN '语文' THEN [Source] ELSE 0 END) AS '[语文]'

  FROM [TestRows2Columns]

  GROUP BY [UserName]

  GO

wps_clip_image-14456

  (图3:样本数据)

  (三) 接着以动态的方式实现行转列,这是使用拼接SQL的方式实现的,所以它适用于SQL Server 2000以上的数据库版本,执行脚本返回的结果如图2所示;

  --2:动态拼接行转列

  DECLARE @sql VARCHAR(8000)

  SET @sql = 'SELECT [UserName],'

  SELECT @sql = @sql + 'SUM(CASE [Subject] WHEN '''+[Subject]+''' THEN [Source] ELSE 0 END) AS '''+QUOTENAME([Subject])+''','

  FROM (SELECT DISTINCT [Subject] FROM [TestRows2Columns]) AS a

  SELECT @sql = LEFT(@sql,LEN(@sql)-1) + ' FROM [TestRows2Columns] GROUP BY [UserName]'

  PRINT(@sql)

  EXEC(@sql)

  GO

  (四) 在SQL Server 2005之后有了一个专门的PIVOT 和 UNPIVOT 关系运算符做行列之间的转换,下面是静态的方式实现的,实现效果如图4所示:

  --3:静态PIVOT行转列

  SELECT *

  FROM ( SELECT [UserName] ,

  [Subject] ,

  [Source]

  FROM [TestRows2Columns]

  ) p PIVOT

  ( SUM([Source]) FOR [Subject] IN ( [数学],[英语],[语文] ) ) AS pvt

  ORDER BY pvt.[UserName];

  GO

  (图4)

  (五) 把上面静态的SQL基础上进行修改,这样就不用理会记录里面存储了什么,需要转成什么列名的问题了,脚本如下,效果如图4所示:

  --4:动态PIVOT行转列

  DECLARE @sql_str VARCHAR(8000)

  DECLARE @sql_col VARCHAR(8000)

  SELECT @sql_col = ISNULL(@sql_col + ',','') + QUOTENAME([Subject]) FROM [TestRows2Columns] GROUP BY [Subject]

  SET @sql_str = '

  SELECT * FROM (

  SELECT [UserName],[Subject],[Source] FROM [TestRows2Columns]) p PIVOT

  (SUM([Source]) FOR [Subject] IN ( '+ @sql_col +') ) AS pvt

  ORDER BY pvt.[UserName]'

  PRINT (@sql_str)

  EXEC (@sql_str)

  (六) 也许很多人到了上面一步就够了,但是你会发现,当别人拿到你的代码,需要不断的修改成他自己环境中表名、分组列、行转列字段、字段值这几个参数,逻辑如图5所示,所以,我继续对上面的脚本进行修改,你只要设置自己的参数就可以实现行转列了,效果如图4所示:

  --5:参数化动态PIVOT行转列

  -- =============================================

  -- Author:

  -- Create date:

  -- Description:

  -- Blog:

  -- =============================================

  DECLARE @sql_str NVARCHAR(MAX)

  DECLARE @sql_col NVARCHAR(MAX)

  DECLARE @tableName SYSNAME --行转列表

  DECLARE @groupColumn SYSNAME --分组字段

  DECLARE @row2column SYSNAME --行变列的字段

  DECLARE @row2columnValue SYSNAME --行变列值的字段

  SET @tableName = 'TestRows2Columns'

  SET @groupColumn = 'UserName'

  SET @row2column = 'Subject'

  SET @row2columnValue = 'Source'

  --从行数据中获取可能存在的列

  SET @sql_str = N'

  SELECT @sql_col_out = ISNULL(@sql_col_out + '','','''') + QUOTENAME(['+@row2column+'])

  FROM ['+@tableName+'] GROUP BY ['+@row2column+']'

  --PRINT @sql_str

  EXEC sp_executesql @sql_str,N'@sql_col_out NVARCHAR(MAX) OUTPUT',@sql_col_out=@sql_col OUTPUT

  --PRINT @sql_col

  SET @sql_str = N'

  SELECT * FROM (

  SELECT ['+@groupColumn+'],['+@row2column+'],['+@row2columnValue+'] FROM ['+@tableName+']) p PIVOT

  (SUM(['+@row2columnValue+']) FOR ['+@row2column+'] IN ( '+ @sql_col +') ) AS pvt

  ORDER BY pvt.['+@groupColumn+']'

  --PRINT (@sql_str)

  EXEC (@sql_str)

wps_clip_image-17757

  (图5)

  (七) 在实际的运用中,我经常遇到需要对基础表的数据进行筛选后再进行行转列,那么下面的脚本将满足你这个需求,效果如图6所示:

  --6:带条件查询的参数化动态PIVOT行转列

  -- =============================================

  -- Author:

  -- Create date:

  -- Description:

  -- Blog:

  -- =============================================

  DECLARE @sql_str NVARCHAR(MAX)

  DECLARE @sql_col NVARCHAR(MAX)

  DECLARE @sql_where NVARCHAR(MAX)

  DECLARE @tableName SYSNAME --行转列表

  DECLARE @groupColumn SYSNAME --分组字段

  DECLARE @row2column SYSNAME --行变列的字段

  DECLARE @row2columnValue SYSNAME --行变列值的字段

  SET @tableName = 'TestRows2Columns'

  SET @groupColumn = 'UserName'

  SET @row2column = 'Subject'

  SET @row2columnValue = 'Source'

  SET @sql_where = 'WHERE UserName = ''王五'''

  --从行数据中获取可能存在的列

  SET @sql_str = N'

  SELECT @sql_col_out = ISNULL(@sql_col_out + '','','''') + QUOTENAME(['+@row2column+'])

  FROM ['+@tableName+'] '+@sql_where+' GROUP BY ['+@row2column+']'

  --PRINT @sql_str

  EXEC sp_executesql @sql_str,N'@sql_col_out NVARCHAR(MAX) OUTPUT',@sql_col_out=@sql_col OUTPUT

  --PRINT @sql_col

  SET @sql_str = N'

  SELECT * FROM (

  SELECT ['+@groupColumn+'],['+@row2column+'],['+@row2columnValue+'] FROM ['+@tableName+']'+@sql_where+') p PIVOT

  (SUM(['+@row2columnValue+']) FOR ['+@row2column+'] IN ( '+ @sql_col +') ) AS pvt

  ORDER BY pvt.['+@groupColumn+']'

  --PRINT (@sql_str)

  EXEC (@sql_str)

  (图6)

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Fix: Windows 11's dynamic refresh rate doesn't work Fix: Windows 11's dynamic refresh rate doesn't work Apr 13, 2023 pm 08:52 PM

You can measure a screen's refresh rate by counting the number of times the image updates per second. DRR is a new feature included in Windows 11 that helps you save battery life while still providing a smoother display, but it's no surprise when it doesn't work properly. Screens with higher refresh rates are expected to become more common as more manufacturers announce plans to stop producing 60Hz monitors. This will result in smoother scrolling and better gaming, but it will come at the cost of reduced battery life. However, the dynamic refresh rate feature in this iteration of the OS is a nifty addition that can have a big impact on your overall experience. Read on as we discuss what to do if Windows 11’s dynamic refresh rate isn’t working

How to Hide Dynamic Island and Red Indicator in iPhone Screen Recording How to Hide Dynamic Island and Red Indicator in iPhone Screen Recording Apr 13, 2023 am 09:13 AM

On iPhone, Apple's screen recording feature records a video of what you're doing on the screen, which is useful if you want to capture gameplay, walk someone through a tutorial in an app, demonstrate a bug, or anything else. On older iPhones that have a notch at the top of the display, the notch is not visible in screen recording, as it should be. But on newer iPhones with the ‌Dynamic Island‌ cutout, such as the ‌iPhone 14 Pro‌ and ‌iPhone 14 Pro‌ Max, the ‌Dynamic Island‌ animation displays the red recording indicator, which causes the cutout to be visible in captured videos. this might

Convert VirtualBox fixed disk to dynamic disk and vice versa Convert VirtualBox fixed disk to dynamic disk and vice versa Mar 25, 2024 am 09:36 AM

When creating a virtual machine, you will be asked to select a disk type, you can select fixed disk or dynamic disk. What if you choose fixed disks and later realize you need dynamic disks, or vice versa? Good! You can convert one to the other. In this post, we will see how to convert VirtualBox fixed disk to dynamic disk and vice versa. A dynamic disk is a virtual hard disk that initially has a small size and grows in size as you store data in the virtual machine. Dynamic disks are very efficient at saving storage space because they only take up as much host storage space as needed. However, as disk capacity expands, your computer's performance may be slightly affected. Fixed disks and dynamic disks are commonly used in virtual machines

How to convert dynamic disk to basic disk on Windows 11 How to convert dynamic disk to basic disk on Windows 11 Sep 23, 2023 pm 11:33 PM

If you want to convert a dynamic disk to a basic disk in Windows 11, you should create a backup first as the process will erase all data in it. Why should you convert dynamic disk to basic disk in Windows 11? According to Microsoft, dynamic disks have been deprecated from Windows and their use is no longer recommended. Additionally, Windows Home Edition does not support dynamic disks, so you will not be able to access these logical drives. If you want to combine more disks into a larger volume, it is recommended to use Basic Disks or Storage Spaces. In this article, we will show you how to convert dynamic disk to basic disk on Windows 11 How to convert dynamic disk to basic disk in Windows 11? In the beginning

How to install, uninstall, and reset Windows server backup How to install, uninstall, and reset Windows server backup Mar 06, 2024 am 10:37 AM

WindowsServerBackup is a function that comes with the WindowsServer operating system, designed to help users protect important data and system configurations, and provide complete backup and recovery solutions for small, medium and enterprise-level enterprises. Only users running Server2022 and higher can use this feature. In this article, we will explain how to install, uninstall or reset WindowsServerBackup. How to Reset Windows Server Backup If you are experiencing problems with your server backup, the backup is taking too long, or you are unable to access stored files, then you may consider resetting your Windows Server backup settings. To reset Windows

How to Get Live Tiles on the Desktop and Start Menu in Windows 11 How to Get Live Tiles on the Desktop and Start Menu in Windows 11 Apr 14, 2023 pm 05:07 PM

Imagine you are looking for something on your system but are not sure which application to open or select. This is where the Live Tiles feature comes into play. A live tile for any supported application can be added to the desktop or Windows system's Start menu, with its tiles changing frequently. LiveTiles make application widgets come alive in a very pleasing way. Not just for its appearance, but even for convenience. Suppose you are using whatsapp or facebook application on your system, wouldn't it be convenient if the number of notifications is displayed on the application icon? This is possible if any such supported app is added as a live tile. Let’s see how to do it in Windows

How to disable dynamic display of folders and files to prevent quick access in Windows 10 and 11? How to disable dynamic display of folders and files to prevent quick access in Windows 10 and 11? May 06, 2023 pm 04:58 PM

Microsoft introduced Quick Access in Windows 10 and retained the feature in the recently released Windows 11 operating system. Quick Access replaces the Favorites system in File Explorer. One of the core differences between the two features is that Quick Access adds a dynamic component to its list. Some folders appear permanently, while others appear based on usage. Fixed folders are displayed with a pin icon, while dynamic folders do not have such an icon. You can see a comparison between My Favorites and Quick Access here for more details. Quick Access is more powerful than Favorites, but dynamic folder lists add an element of clutter to it. Files that are useless or should not be highlighted in File Explorer may be displayed

How to use Dynamic Lock on Windows 11 How to use Dynamic Lock on Windows 11 Apr 13, 2023 pm 08:31 PM

What is dynamic locking on Windows 11? Dynamic Lock is a Windows 11 feature that locks your computer when a connected Bluetooth device (your phone or wearable) goes out of range. The Dynamic Lock feature automatically locks your PC even if you forget to use the Windows Key + L shortcut while walking away. Dynamic Lock works with any connected device with Bluetooth, but it's best to use a device with enough battery power and range, such as your phone. Once your device becomes inaccessible for 30 seconds, Windows will automatically lock the screen. Pair a Bluetooth device with Windows 11 For everything to work properly, you need to first

See all articles