SQL中的反向表

时间:2018-04-26 10:20:40

标签: sql sql-server

我有疑问:

SELECT DISTINCT temp.ID,request.RequestTypeID
FROM @MyTempTable6 as temp
JOIN dbo.FingerMachineUsers as fingeruser
ON temp.UserNo = fingeruser.ID
JOIN dbo.AppUsers as appuser
ON appuser.Id = fingeruser.UserId
LEFT JOIN dbo.Requests as request
ON request.UserId = fingeruser.UserId 

结果:

enter image description here

如何创建这样的表:

ID|RequestTypeID1|RequestTypeID2
1 |             4|             5

4 个答案:

答案 0 :(得分:0)

如果您只有两个值,那么最简单的方法是聚合:

SELECT t.ID, MIN(r.RequestTypeID), MAX(r.RequestTypeID)
FROM @MyTempTable6 t JOIN
     dbo.FingerMachineUsers fu
     ON t.UserNo = fu.ID JOIN
     dbo.AppUsers au
     ON au.Id = fu.UserId LEFT JOIN
     dbo.Requests r
     ON r.UserId = fu.UserId
GROUP BY t.ID;

如果您想要呈现可变数量的值,则查询会复杂得多。

答案 1 :(得分:0)

PIVOT运算符可能是你最好的朋友,如果每个只有2个值......

答案 2 :(得分:0)

尝试此查询...

免责声明:此代码纯粹基于此答案。 (https://stackoverflow.com/a/10404455/6327676

DECLARE @cols  AS NVARCHAR(max), 
        @query AS NVARCHAR(max); 

SET @cols = Stuff((SELECT DISTINCT ',' + Quotename(stff.requesttypeid)
                   FROM   TableName stff
                   FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, '' 
            ) 
SET @query = 'SELECT ID, '+ @cols
             + ' FROM (select ID, RequestTypeId FROM TableName) x pivot (MAX(RequestTypeId) FOR RequestTypeId in (' 
             + @cols + ')) p' 

EXECUTE(@query) 

答案 3 :(得分:0)

尝试此代码,它将根据您想要的结果工作。 首先,您需要将@ MyTempTable6表转储到#temptable中 然后在@colums varible中将RequestTypeID列设置为逗号分隔,然后在@Requestcolumns变量中设置列名,然后使用pivot。

DECLARE @colums AS NVARCHAR(max)
DECLARE @Requestcolumns AS NVARCHAR(max)
DECLARE @query AS NVARCHAR(max);


SELECT DISTINCT temp.ID,request.RequestTypeID
into #temptable
FROM @MyTempTable6 as temp
JOIN dbo.FingerMachineUsers as fingeruser
ON temp.UserNo = fingeruser.ID
JOIN dbo.AppUsers as appuser
ON appuser.Id = fingeruser.UserId
LEFT JOIN dbo.Requests as request
ON request.UserId = fingeruser.UserId  

SET @colums = Stuff((SELECT DISTINCT ',' +Quotename(tab.RequestTypeID)
                   FROM   #temptable tab
                   FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, '' 
            )      

SET @Requestcolumns = Stuff((SELECT DISTINCT ',' +Quotename(tab.RequestTypeID) +' AS ',+Quotename('RequestTypeID'+CONVERT(varchar(100),tab.RequestTypeID))
                   FROM   #temptable tab
                   FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, '' 
            ) 

SET @query = 'SELECT ID, '+@Requestcolumns
             + ' FROM (select ID, RequestTypeID FROM #temptable) x pivot (MAX(RequestTypeID) FOR RequestTypeID in (' 
             + @colums + ')) p' 

EXECUTE(@query) 

DROP table #temptable