0

采购线有

itemid, deliverydate, qtyordered

select * from purchline
itemid   deliverydate    qtyordered
74700    01/01/2000      50
74700    01/01/2007      51
74700    01/01/2010      5

问。

我更愿意将其视为一个存储过程,如下所示:

itemid  deliverydates                     TotalOrdered 
74700   01/01/2000 01/01/2007 01/01/2010  106
4

2 回答 2

1

如果您使用的是 MySQL:

SELECT   ItemID, 
         GROUP_CONCAT(deliverydate SEPARATOR ' ') as deliverydate,
         SUM(qtyordered) qtyordered
FROM     purchline
GROUP BY ItemID
于 2012-07-23T03:14:40.470 回答
1

为 SQL Server 2005 编辑

如果您使用的是 SQL Server:

SELECT itemid
    ,deliverydates = STUFF((SELECT ' ' + CONVERT(NVARCHAR, deliverydate, 101)
                           FROM purchline b 
                           WHERE b.itemid = a.itemid
                           FOR XML PATH('')), 1, 1, '')
    ,TotalOrdered = SUM(qtyordered) 
FROM purchline a
GROUP BY itemid

使用以下内容进行测试:

-- Setup test data
DECLARE @T1 AS TABLE (
    itemid NVARCHAR(50)
    ,deliverydate DATETIME
    ,qtyordered INT);

INSERT @T1 VALUES ('74700', '20000101', 50)
INSERT @T1 VALUES ('74700', '20070101', 51)
INSERT @T1 VALUES ('74700', '20100101', 5)

-- Return the desired results
SELECT itemid
    ,deliverydates = STUFF((SELECT ' ' + CONVERT(NVARCHAR, deliverydate, 101)
                           FROM @T1 b 
                           WHERE b.itemid = a.itemid
                           FOR XML PATH('')), 1, 1, '')
    ,TotalOrdered = SUM(qtyordered) 
FROM @T1 a
GROUP BY itemid
于 2012-07-23T03:09:19.270 回答