SQL Server - 如何在列中显示主详细信息数据

时间:2010-03-10 02:06:06

标签: sql-server master-detail

我有两个表,简洁一点,我们称之为TableA和TableB。这是架构:

TableA
ID – int
Name varchar(50)

TableB
ID – int
TableA_Fk – int
Value varchar(50)

表A中的每条记录在表B中最多只能有9条记录。我希望能够以柱状形式检索数据:

TableA-Name, TableB-Value1, … TableB-Value9

这可以使用查询吗?谢谢!

3 个答案:

答案 0 :(得分:0)

您需要LEFT JOIN和PIVOT表

答案 1 :(得分:0)

您可以执行以下操作:

SELECT rank() OVER (ORDER BY tableA_FK) as rank, tableA_fk, value
INTO #temp
FROM TableB b
ORDER BY rank 


SELECT a.Name, 
       CASE WHEN t.rank = 1 THEN t.Value ELSE NULL END AS TableB-Value1,
       CASE WHEN t.rank = 2 THEN t.Value ELSE NULL END AS TableB-Value2,
       CASE WHEN t.rank = 3 THEN t.Value ELSE NULL END AS TableB-Value3,
       .... (etc.)
FROM TableA a
INNER JOIN #temp t ON a.Id = t.tableA_fk

您需要Sql Server 2005或更高版本。 对不起,但我没有Sql Server(或时间)来测试这个。希望这会给你一个想法和帮助。

答案 2 :(得分:0)

除了DBRM独立外,还应该这样做。

SELECT A.Name
    , SUM(CASE WHEN B.Value = 1 THEN 1 ELSE NULL END) AS B_Value_1
    , SUM(CASE WHEN B.Value = 2 THEN 2 ELSE NULL END) AS B_Value_2
    , SUM(CASE WHEN B.Value = 3 THEN 3 ELSE NULL END) AS B_Value_3
    , SUM(CASE WHEN B.Value = 4 THEN 4 ELSE NULL END) AS B_Value_4
    , SUM(CASE WHEN B.Value = 5 THEN 5 ELSE NULL END) AS B_Value_5
    , SUM(CASE WHEN B.Value = 6 THEN 6 ELSE NULL END) AS B_Value_6
    , SUM(CASE WHEN B.Value = 7 THEN 7 ELSE NULL END) AS B_Value_7
    , SUM(CASE WHEN B.Value = 8 THEN 8 ELSE NULL END) AS B_Value_8
    , SUM(CASE WHEN B.Value = 9 THEN 9 ELSE NULL END) AS B_Value_9
FROM A
    INNER JOIN B ON B.TableA_FK = A.ID
GROUP BY A.Name
ORDER BY A.Name