在存储过程

时间:2017-07-08 08:30:33

标签: sql-server stored-procedures

我有以下三个表,我想使用存储过程作为最后一个表。谁能告诉我如何加入他们?

光盘

DiscId  DiscName
1         a
2         b
3         c

DiscDetail

DiscDetailId  DiscId  DiscDetailName  Percentage
1             1       p               5
2             1       q               10
3             2       r               12
4             2       s               11
5             2       t               13
6             3       u               19
7             3       v               20

PurId  DiscId
1      1
2      2
3      1
4      1

我想按如下方式显示数据:

PurId  p  q   r   s   t
1      5  10  
2             12  11  13
3      5  10
4      5  10

2 个答案:

答案 0 :(得分:0)

SELECT PurId ,
CASE WHEN DD.DiscDetailName ='P' THEN DD.Percentage END 'P',
CASE WHEN DD.DiscDetailName ='q' THEN DD.Percentage END 'q',
CASE WHEN DD.DiscDetailName ='r' THEN DD.Percentage END 'r',
CASE WHEN DD.DiscDetailName ='s' THEN DD.Percentage END 's',
CASE WHEN DD.DiscDetailName ='t' THEN DD.Percentage END 't'
FROM
(
SELECT * FROM DISC_DETAIL D
INNER JOIN  CHILD_TABLE CT ON DD.DiscId =CT.DiscId
)DD

尝试以上查询。 希望这会对你有所帮助。

答案 1 :(得分:0)

使用动态旋转:

首先声明所有列:

DECLARE @Columns AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX);

    SET @Columns = STUFF((SELECT distinct ',' + QUOTENAME(c.DiscDetailName  ) 
                FROM DiscDetail c
                FOR XML PATH(''), TYPE
                ).value('.', 'NVARCHAR(MAX)') 
            ,1,1,'')

创建动态支点:

set @query = 'SELECT PurId, ' + @Columns + ' from 
                (
                    select Pur.PurId
                        , DiscDetail.Percentage
                        , DiscDetail.DiscDetailName
                    from Pur 
                    inner join Disc on Pur.DiscID = Disc.DiscId  
                    inner join DiscDetail  on DiscDetail.ID = Disc.DiscId  
               ) x
                pivot 
                (
                     max(Percentage)
                    for DiscDetailName in (' + @Columns + ')
                ) p '


    execute(@query)