(TRANSACT SQL)如何使用sql连续创建Master-Detail?

时间:2011-11-08 09:22:13

标签: sql sql-server tsql

我有两张桌子

table1
------
ID
NAME
ADDRESS

table2
-------
ID
PHONE
EMAIL

我该如何创建这样的报告

------------------------------------


01   Dave   123 Veneu

     555-5  A@YAHOO.COM
     66-66  B@Yahoo.co.id
     213-1  D@c.com


02   John   23 Park

     322-1  C@you.com
     54-23  D@Net.com
     231-2  me@you.com

即时通讯使用sql server 2005 express,谢谢你提前。

3 个答案:

答案 0 :(得分:1)

不确定为什么你会想要在报告设计师以外的任何地方写这个,但仅仅是为了它的地狱:

SELECT ID AS Column1, NAME AS Column2, Address AS Column3, ID AS SortColumn1, 1 AS SortColumn2
UNION
SELECT '', PHONE, EMAIL, ID AS SortColumn1, 2 AS SortColumn2
ORDER BY SortColumn1, SortColumn2

输出实际上基本上是一堆乱码,你最后还有两个额外的列可以摆脱它。

答案 1 :(得分:1)

你不应该。这是一般原则,不应在数据库层中进行格式化。

应该使用SQL Server生成数据,然后您的应用程序应该处理数据,包括格式化。

我会打开两个查询。一个加载表一,按ID列排序。另一个加载表二,也按ID列排序。然后,您可以同时遍历两个记录集,类似于以下伪代码...

rs1 = SQL.Execute("SELECT * FROM table1 ORDER BY ID")
rs2 = SQL.Execute("SELECT * FROM table2 ORDER BY ID, phone")

rs2.Next()
WHILE rs1.Next()
  Output The Address Info Here
  WHILE rs1.ID = rs2.ID
    Output The Phone/Email Info Here
    rs2.Next()
  END WHILE
END WHILE

答案 2 :(得分:0)

我非常同意dems,但如果你真的需要提出类似的东西,下面的内容可能会有效(尽管没有空行)

 SELECT case 
            when group_rn = 1 then id 
            else ''
        end as id, 
        case 
          when group_rn = 1 then name
          else phone 
        end as name_phone_column, 
        case 
          when group_rn = 1 then address
          else _email 
        end as address_email_column
 FROM (
     SELECT t1.id,
            t1.name,
            t1.address,
            t2.email,
            t2.phone, 
            row_number() over (partition by t1.id order t1.name) as group_rn
     FROM table1 t1
        LEFT JOIN table2 t2 ON t1.id = t2.id
 ) t
 ORDER BY id

这假定phonename都具有相同的数据类型,就像addressemail一样。