我有一个表订单,它有以下列:
OrderID, ClientID, BankNumber, Adres, Name;
我想写一个给我这个结果的查询:一行中有明确的clientid名称和adres以及所有归属订单和一行上相应的bankaccount数字:这是我的例子。
ClientID Adres Name order1 Banknumber Order2 Banknumber order3 Banknumber
答案 0 :(得分:1)
首先,您无法查询某些内容并提出具有无限列数的结果集,但您可以将订单合并并在1列中显示。
如果你在SQL Azure或SQL2017上,你也可以像这样使用STRING_AGG:
select customer.Id, customer.Name, orderSummary.orderData
(select STRING_AGG(orderID+'-'+banknumber+', ') as orderData from orders where customerId = customer.Id) orderSummary
from Customers as customer
您可以查看此帖子以获取更多答案 How to concatenate text from multiple rows into a single text string in SQL server? 和Microsoft的子查询: https://technet.microsoft.com/en-us/library/ms189575(v=sql.105).aspx
答案 1 :(得分:0)
这是一份工作样本。 希望对你有效。
您需要动态构建Order1,order2,order3 ...和BankNumber1,BankNumber2 ....我在我的例子中有硬编码
drop table #t1
create table #t1(OrderID Int, ClientID int, BankNumber varchar(50), [Address] varchar(50), Name varchar(50))
insert into #t1
select 1,11,'111','xyz1','xyz'
union all
select 2,22,'112','xyz2','xyzz'
union all
select 3,33,'113','xyz3','xyzzz'
union all
select 100,11,'111','xyz1','xyz'
union all
select 200,22,'112','xyz2','xyzz'
union all
select 300,33,'113','xyz3','xyzzz'
;with cte as
(
select OrderID,ClientID,BankNumber,Address,Name,ROW_NUMBER()over (partition by clientid order by orderid asc) RN
from #t1
)
select ClientID
,max([Order 1]) Order1
,max([Order 2]) Order2
,max([BankNumber 1]) BankNumber1
,max([BankNumber 2]) BankNumber2
from
(
select ClientID,Address,Name,OrderID,BankNumber,'Order '+cast(rn as varchar(10)) OrderSeq
,'BankNumber '+cast(rn as varchar(10)) BankNumberSeq
from cte
) as ST
pivot(max(OrderID) for OrderSeq in ([Order 1],[Order 2])) as pt1
pivot(max(BankNumber) for BankNumberSeq in ([BankNumber 1],[BankNumber 2])) as pt2
group by ClientID