需要有关编写SQL Server查询的帮助

时间:2010-12-09 12:27:53

标签: sql tsql sql-server-2008

有两个表,

表A

A_ID    A_Field  
1          blah1  
2          blah2  
3          blah3  
........

=============================================== =============

表B(A_ID是外键引用表A的A_ID)

A_ID  B_Field  
1      a   
1      b  
1      c  
2      a  
2      b  
2      c  

获得如下结果的最佳方式是什么:

A_ID   A_Field   B_Field  
1        blah1       a,b,c  
2        blah2       a,b,c

非常感谢回复,它们都有效,但是,还有一个请求,“For XML”dows不能用于SQL SERVER 2000,不幸的是我的域服务的数据库是SQL Server 2000,是否有一个简单的查询工作在SQL SERVER 2000上?谢谢!

6 个答案:

答案 0 :(得分:0)

“最佳”是一个相对术语。我可能会使用多个查询并在代码中连接字符串。

您可以创建一个以A_ID作为参数的标量UDF,并从表B构建非规范化字符串。您的最终SELECT将是:

SELECT A.A_ID, A.A_Field, dbo.myUDF(A.A_ID)
FROM A

答案 1 :(得分:0)

要获得结果,因为您要求您需要加入两个表格。这是一个例子:

SELECT A_ID, A_FIELD, B_FIELD 
FROM Table A
LEFT JOIN Table B ON Table A.A_ID = Table B.A_ID

答案 2 :(得分:0)

尝试类似(*完整示例*)

DECLARE @TableA TABLE(
        A_ID INT,
        A_Field VARCHAR(20)
)
INSERT INTO @TableA SELECT 1,'blah1'
INSERT INTO @TableA SELECT 2,'blah2'
INSERT INTO @TableA SELECT 3,'blah3'

DECLARE @TableB TABLE(
        A_ID INT,
        B_Field VARCHAR(20)
)
INSERT INTO @TableB SELECT 1,'a'
INSERT INTO @TableB SELECT 1,'b'
INSERT INTO @TableB SELECT 1,'c'
INSERT INTO @TableB SELECT 2,'a'
INSERT INTO @TableB SELECT 2,'b'
INSERT INTO @TableB SELECT 2,'c'

;WITH Vals AS (
    SELECT  a.A_ID,
            a.A_Field,
            b.B_Field
    FROM    @TableA a INNER JOIN
            @TableB b ON a.A_ID = b.A_ID
)
SELECT  p1.A_ID,
        p1.A_Field
        ,STUFF( 
               (SELECT 
                    ', ' + p2.B_Field 
                    FROM Vals p2 
                    WHERE p2.A_ID=p1.A_ID 
                    ORDER BY p2.A_ID 
                    FOR XML PATH(''), TYPE 
               ).value('.','varchar(max)') 
               ,1,2, '' 
          ) AS B_Field 
FROM Vals p1 
GROUP BY    p1.A_ID,
            p1.A_Field

输出

A_ID    A_Field B_Field
1   blah1   a, b, c
2   blah2   a, b, c

答案 3 :(得分:0)

你将使用group by函数来连接列B_Field值,你可以参考this关于使用cancatenating字符串的帖子

答案 4 :(得分:0)

我不知道这是不是最好的方法,但它有效:

declare @rv table (a_id int, a_field varchar(50), b_field varchar(50))
insert into @rv (a_id, a_field) select a_id, a_field from a

declare @id int
declare @b varchar(50)
declare cur cursor for select a_id from @rv
open cur
fetch next from cur into @id
while @@fetch_status = 0 begin
  set @b = ''
  select @b = @b + ',' + b_field from b where a_id = @id
  if len(@b) > 1 set @b = substring(@b, 2, len(@b)-1)
  update @rv set b_field = @b where a_id = @id
  fetch next from cur into @id
end
close cur
deallocate cur
select * from @rv

答案 5 :(得分:0)

SELECT a.A_ID
     , a.A_Field
     , (SELECT CAST(b.B_Field+ ', ' AS VARCHAR(MAX)) 
         FROM table_B b
         WHERE (a.A_ID= b.A_ID) 
         FOR XML PATH ('')
      )AS whatever FROM table_a a

这应该可以随意使用。干杯。 试试这个

How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?