比如说我有一个订单加上多个项目。 如何在同一行列出它们(例如3个项目)?
我已经尝试过这个
SELECT order.ID, item.name , item.qty , item2.name,item2.qty,item3.name,item3.qty
FROM order
JOIN item ON order.id = item.id
JOIN item as item2 ON order.id = item2.id
JOIN item as item3 ON order.id = item3.id
但是如何避免多次选择同一个项目?
提前致谢
答案 0 :(得分:0)
在TSQL中,您可以将查询编写为:
DECLARE @order TABLE (id int)
INSERT INTO @order VALUES (1)
DECLARE @item TABLE (id INT,NAME VARCHAR(10),qty INT)
INSERT INTO @item VALUES (1,'A',1),(1,'B',1),(1,'C',3)
SELECT
O.id AS OrderId,
STUFF
(
(
SELECT ', Name:' + NAME + ', Qty:' + CAST (qty AS VARCHAR(10))
FROM @item I
WHERE I.Id = O.Id
ORDER BY I.Id
FOR XML PATH(''), type
).value('.', 'varchar(max)'), 1, 1, ''
) AS Models
FROM
@order O