我在SQL Server 2008中有一个如下表:
location LOB UnitName
---------- --------- -------------------
Chennai Health UnitB
Mumbai Health UnitB
Pune Health UnitA,UnitB
Chennai Motor UnitB
Mumbai Motor UnitB
Pune Motor UnitB,UnitC
Trivandum Motor UnitC
我期待下面的结果..
Location Health Motor
--------- -------- --------
Chennai UnitB UnitB
Mumbai UnitB UnitB
Pune UnitA,UnitB UnitB,UnitC
Trivandum UnitC
我需要一个像这样显示的查询。任何人都可以帮助我实现这个目标吗?
答案 0 :(得分:0)
试试这个:
SELECT DISTINCT location,
ISNULL((SELECT UnitName FROM table_name t1 WHERE t1.location=t.location AND t1.LOB= 'Health'),'') AS Health,
ISNULL((SELECT UnitName FROM table_name t2 WHERE t2.location=t.location AND t2.LOB= 'Motor'),'') AS Motor
FROM table_name t
答案 1 :(得分:0)
要转动表格,您需要对轮播值使用聚合函数,而评论中的代码中缺少这些值。在您的情况下,您可以使用MAX()
SELECT *
FROM(
SELECT location, LOB, UnitName
FROM @t
) AS t
PIVOT(
MAX(UnitName)
FOR LOB IN([Health], [Motor])
) AS pivotTable
对于动态列,请尝试以下操作:
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
SELECT @ColumnName= ISNULL(@ColumnName + ',','')
+ QUOTENAME(LOB)
FROM (SELECT DISTINCT LOB FROM @t) AS Courses
SET @DynamicPivotQuery =
'SELECT *
FROM(
SELECT location, LOB, UnitName
FROM @t
) AS t
PIVOT(
MAX(UnitName)
FOR LOB IN(' + @ColumnName + ')
) AS pivotTable
ORDER BY Location DESC'
EXEC sp_executesql @DynamicPivotQuery
答案 2 :(得分:0)
我做的最简单的方法是以下查询:
SELECT DISTINCT MAIN.location, ISNULL(HEALTH.UnitName, '') as [HEALTH], ISNULL(Motor.UnitName, '') as [Motor]
FROM
(Select location from unitlocation ) AS MAIN
LEFT OUTER JOIN
(SELECT location, UnitName from unitlocation where LOB = 'Health') AS HEALTH ON MAIN.location = HEALTH.location
LEFT OUTER JOIN
(SELECT location, UnitName from unitlocation where LOB = 'Motor') AS Motor ON MAIN.location = Motor.location
以下是工作演示 CLICK HERE
DYNAMIC GENERATION
请为动态栏目找到工作演示:
DECLARE @cols VARCHAR(MAX)
;WITH CTE
AS
(
SELECT
ROW_NUMBER() OVER(PARTITION BY [LOB] ORDER BY [LOB]) AS RowNbr,
LOB,
UNITNAME
FROM
unitlocation
)
SELECT @cols=STUFF
(
(
SELECT
',' +QUOTENAME([LOB])
FROM
CTE
WHERE
CTE.RowNbr=1
FOR XML PATH('')
)
,1,1,'')
DECLARE @query NVARCHAR(4000)=
N'SELECT
*
FROM
(
SELECT
unitlocation.location,
unitlocation.LOB,
unitlocation.UnitName
FROM
unitlocation
) AS p
PIVOT
(
MAX(UnitName)
FOR LOB IN ('+@cols+')
) AS pvt'
EXECUTE(@query)