一列保存多個ID(將多個用逗號隔開的ID轉換成用逗號隔開的名稱)_Mssql數據庫教程
教程Tag:暫無Tag,歡迎添加,賺取U幣!
推薦:經典SQL語句大全一、基礎 1、說明:創建數據庫 CREATE DATABASE database - name 2、說明:刪除數據庫 drop database dbname 3、說明:備份sql server -- - 創建 備份數據的 device USE master EXEC sp_addumpdevice ' disk ' , ' testBack ' , ' c:\mssql7backup\MyNwind_1.dat ' --
背景:在做項目時,經常會遇到這樣的表結構在主表的中有一列保存的是用逗號隔開ID。如,當一個員工從屬多個部門時、當一個項目從屬多個城市時、當一個設備從屬多個項目時,很多人都會在員工表中加入一個deptIds VARCHAR(1000)列(本文以員工從屬多個部門為例),用以保存部門編號列表(很明顯這不符合第一范式,但很多人這樣設計了,在這篇文章中我們暫不討論在這種應用場景下,如此設計的對與錯,有興趣的可以在回復中聊聊),然后我們在查詢列表中需要看到這個員工從屬哪些部門。初始化數據:
部門表、員工表數據:
- IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Department]'))
- DROP TABLE [dbo].Department
- GO
- --部門表
- CREATE TABLE Department
- (
- id int,
- name nvarchar(50)
- )
- INSERT INTO Department(id,name)
- SELECT 1,'人事部'
- UNION
- SELECT 2,'工程部'
- UNION
- SELECT 3,'管理部'
- SELECT * FROM Department
- IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Employee]'))
- DROP TABLE [dbo].Employee
- GO
- --員工表
- CREATE TABLE Employee
- (
- id int,
- name nvarchar(20),
- deptIds varchar(1000)
- )
- INSERT INTO Employee(id,name,deptIds)
- SELECT 1,'蔣大華','1,2,3'
- UNION
- SELECT 2,'小明','1'
- UNION
- SELECT 3,'小華',''
- SELECT * FROM Employee
希望得到的結果:
解決方法:
第一步,是得到如下的數據。即將員工表集合與相關的部門集合做交叉連接,其中使用了fun_SplitIds函數(作用是將ids分割成id列表),然后員工集合與這個得到的集合做交叉連接
SELECT E.*,ISNULL(D.name,'') AS deptName FROM Employee AS E OUTER APPLY dbo.fun_SplitIds(E.deptIds) AS DID LEFT JOIN Department AS D ON DID.ID=D.id;
第二步,已經得到了如上的數據,然后要做的就是根據ID分組,并對deptName列做聚合操作,但可惜的是SQL SERVER還沒有提供對字符串做聚合的操作。但想到,我們處理樹形結構數據時,用CTE來做關系數據,做成有樹形格式的數據,如此我們也可以將這個問題轉換成做樹形格式的問題,代碼如下:
結果如下:
- WITH EmployeT AS(
- --員工的基本信息(使用OUTER APPLY將多個ID拆分開來,然后與部門表相關聯)
- --此時已將員工表所存的IDS分別與部門相關聯,下面需要將此集合中的deptName聚合成一個記錄
- SELECT E.*,ISNULL(D.name,'') AS deptName
- FROM Employee AS E
- OUTER APPLY dbo.fun_SplitIds(E.deptIds) AS DID
- LEFT JOIN Department AS D ON DID.ID=D.id
- ),mike AS(
- SELECT id,name,deptIds,deptName
- ,ROW_NUMBER()OVER(PARTITION BY id ORDER BY id) AS level_num
- FROM EmployeT
- ),mike2 AS(
- SELECT id,name,deptIds,CAST(deptName AS NVARCHAR(100)) AS deptName,level_num
- FROM mike
- WHERE level_num=1
- UNION ALL
- SELECT m.id,m.name,m.deptIds,CAST(m2.deptName+','+m.deptName AS NVARCHAR(100)) AS deptName,m.level_num
- FROM mike AS m
- INNER JOIN mike2 AS m2 ON m.ID=m2.id AND m.level_num=m2.level_num+1
- ),maxMikeByIDT AS(
- SELECT id,MAX(level_num) AS level_num
- FROM mike2
- GROUP BY ID
- )
- SELECT A.id,A.name,A.deptIds,A.deptName
- FROM mike2 AS A
- INNER JOIN maxMikeByIDT AS B ON A.id=B.ID AND A.level_num=B.level_num
- ORDER BY A.id OPTION (MAXRECURSION 0)
全部SQL:
- IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Department]'))
- DROP TABLE [dbo].Department
- GO
- --部門表
- CREATE TABLE Department
- (
- id int,
- name nvarchar(50)
- )
- INSERT INTO Department(id,name)
- SELECT 1,'人事部'
- UNION
- SELECT 2,'工程部'
- UNION
- SELECT 3,'管理部'
- SELECT * FROM Department
- IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Employee]'))
- DROP TABLE [dbo].Employee
- GO
- --員工表
- CREATE TABLE Employee
- (
- id int,
- name nvarchar(20),
- deptIds varchar(1000)
- )
- INSERT INTO Employee(id,name,deptIds)
- SELECT 1,'蔣大華','1,2,3'
- UNION
- SELECT 2,'小明','1'
- UNION
- SELECT 3,'小華',''
- SELECT * FROM Employee
- --創建一個表值函數,用來拆分用逗號分割的數字串,返回只有一列數字的表
- IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fun_SplitIds]'))
- DROP FUNCTION [dbo].fun_SplitIds
- GO
- CREATE FUNCTION dbo.fun_SplitIds(
- @Ids nvarchar(1000)
- )
- RETURNS @t_id TABLE (id VARCHAR(36))
- AS
- BEGIN
- DECLARE @i INT,@j INT,@l INT,@v VARCHAR(36);
- SET @i = 0;
- SET @j = 0;
- SET @l = len(@Ids);
- while(@j < @l)
- begin
- SET @j = charindex(',',@Ids,@i+1);
- IF(@j = 0) set @j = @l+1;
- SET @v = cast(SUBSTRING(@Ids,@i+1,@j-@i-1) as VARCHAR(36));
- INSERT INTO @t_id VALUES(@v)
- SET @i = @j;
- END
- RETURN;
- END
- GO
- ;WITH EmployeT AS(
- --員工的基本信息(使用OUTER APPLY將多個ID拆分開來,然后與部門表相關聯)
- --此時已將員工表所存的IDS分別與部門相關聯,下面需要將此集合中的deptName聚合成一個記錄
- SELECT E.*,ISNULL(D.name,'') AS deptName
- FROM Employee AS E
- OUTER APPLY dbo.fun_SplitIds(E.deptIds) AS DID
- LEFT JOIN Department AS D ON DID.ID=D.id
- ),mike AS(
- SELECT id,name,deptIds,deptName
- ,ROW_NUMBER()OVER(PARTITION BY id ORDER BY id) AS level_num
- FROM EmployeT
- ),mike2 AS(
- SELECT id,name,deptIds,CAST(deptName AS NVARCHAR(100)) AS deptName,level_num
- FROM mike
- WHERE level_num=1
- UNION ALL
- SELECT m.id,m.name,m.deptIds,CAST(m2.deptName+','+m.deptName AS NVARCHAR(100)) AS deptName,m.level_num
- FROM mike AS m
- INNER JOIN mike2 AS m2 ON m.ID=m2.id AND m.level_num=m2.level_num+1
- ),maxMikeByIDT AS(
- SELECT id,MAX(level_num) AS level_num
- FROM mike2
- GROUP BY ID
- )
- SELECT A.id,A.name,A.deptIds,A.deptName
- FROM mike2 AS A
- INNER JOIN maxMikeByIDT AS B ON A.id=B.ID AND A.level_num=B.level_num
- ORDER BY A.id OPTION (MAXRECURSION 0)
分享:SQL Server字符串切割結果: 645002*01 --1 45854 --2 183677
相關Mssql數據庫教程:
- sql 語句練習與答案
- 深入C++ string.find()函數的用法總結
- SQL Server中刪除重復數據的幾個方法
- sql刪除重復數據的詳細方法
- SQL SERVER 2000安裝教程圖文詳解
- 使用sql server management studio 2008 無法查看數據庫,提示 無法為該請求檢索數據 錯誤916解決方法
- SQLServer日志清空語句(sql2000,sql2005,sql2008)
- Sql Server 2008完全卸載方法(其他版本類似)
- sql server 2008 不允許保存更改,您所做的更改要求刪除并重新創建以下表
- SQL Server 2008 清空刪除日志文件(瞬間日志變幾M)
- Win7系統安裝MySQL5.5.21圖解教程
- 將DataTable作為存儲過程參數的用法實例詳解
- 相關鏈接:
- 教程說明:
Mssql數據庫教程-一列保存多個ID(將多個用逗號隔開的ID轉換成用逗號隔開的名稱)。