加入动态支点

时间:2009-05-24 15:48:01

标签: sql sql-server sql-server-2008

跟随一个新问题,其中包含问题为文字,而不是像这样的图像:

Join with dynamic pivot (version 2)

(这个问题是一个图片。右键点击“我有一些有价值的桌子”。:)


alt text http://img36.imageshack.us/img36/4853/77517349.gif

如果添加了新的位置记录,查询应自动运行。谢谢你

3 个答案:

答案 0 :(得分:2)

SELECT
  c.CategoryId AS CID,
  c.CategoryName,
  ISNULL(t.CategoryOrder, 0) AS [Top],
  ISNULL(l.CategoryOrder, 0) AS [Left],
  ISNULL(r.CategoryOrder, 0) AS [Right]
FROM
  Category c
  LEFT JOIN CategoryPosition t ON t.CategoryId = c.CategoryId 
                                  AND t.PositionId = 1
  LEFT JOIN CategoryPosition l ON l.CategoryId = c.CategoryId 
                                  AND l.PositionId = 2
  LEFT JOIN CategoryPosition r ON r.CategoryId = c.CategoryId 
                                  AND r.PositionId = 3

答案 1 :(得分:1)

凌乱,但它有效

select  c.categoryid,c.categoryname
,COALESCE((select top 1 categoryorder from categoryposition where categoryid=c.categoryid and positionid=1),0) as [top]
,COALESCE((select top 1 categoryorder from categoryposition where categoryid=c.categoryid and positionid=2),0) as [left]
,COALESCE((select top 1 categoryorder from categoryposition where categoryid=c.categoryid and positionid=3),0) as [right]   
 from categoryposition cp,category c
where cp.categoryid=c.categoryid
group by c.categoryid,c.categoryname
order by 1

要记住两件事。如果您可以确保每个类别位置最多只有一个位置,那么您可以删除顶部1,但子查询必须返回1行,否则无法工作。

答案 2 :(得分:0)

由于您希望交叉表查询基于Position表的内容是动态的,因此我建议您在运行时动态生成SQL。

-- Start with Query frame
DECLARE @Query NVARCHAR(4000)
SET @Query = '
Select
        Category.CategoryID,
        Category.CategoryName
        <DYNAMICQUERY>
    From CategoryPosition
    Inner Join Category ON Category.CategoryID = CategoryPosition.CategoryID
    Group By Category.CategoryID, Category.CategoryName';

SELECT @Query;


-- Build the dynamic part of query
DECLARE @DynamicQuery VARCHAR(1024)
DECLARE @PositionCol VARCHAR(256)
DECLARE dynamic_sql CURSOR FOR
SELECT ',MAX(CASE WHEN CategoryPosition.PositionID = '+CAST(PositionID AS varchar(10)) +' THEN CategoryPosition.CategoryOrder ELSE 0 END) AS ['+PositionName+']' 
From Position

OPEN dynamic_sql

FETCH NEXT FROM dynamic_sql
INTO @PositionCol

SELECT @DynamicQuery = @PositionCol;

WHILE @@FETCH_STATUS = 0
BEGIN
    FETCH NEXT FROM dynamic_sql
    INTO @PositionCol

    SELECT @DynamicQuery = @DynamicQuery+@PositionCol;
END

CLOSE dynamic_sql
DEALLOCATE dynamic_sql

SELECT @Query = REPLACE(@Query, '<DYNAMICQUERY>', @DynamicQuery)

-- Execute the Query
EXECUTE sp_executesql @Query