将多个结果连接到一个字段

时间:2013-04-28 02:38:06

标签: sql ms-access

我已经recently在将我的发票放在一起很容易看到桌子的路上了。我通常手动完成的东西,但我想自动做的是列出发票上有多少项目。我手动查看发票,看到一只狗在狗窝里停留了3天并洗个澡,所以我在电子表格中放了3 Board, 1 Bath之类的东西。

我所拥有的表格(InvoiceItems.IIItemQuantityInvoiceItems.IIItemCodeDesc)以及它们所属的发票(InvoiceItems.IIInvSeq)。

因此,我想要添加到其他查询中的信息如下所示:

QUANTITY | ITEMDESC | INVOICE | PETID
---------|----------|---------|------
    3    |   BOARD  |  12344  |  12
    1    |    BATH  |  12344  |  12
    4    |   BOARD  |  12345  |  14
    4    |    PLAY  |  12345  |  14
    1    |    BATH  |  12345  |  14
    4    |   BOARD  |  12345  |  15
    2    |    PLAY  |  12345  |  15
    1    |    BATH  |  12345  |  15

这是发票12344有一只狗(petid 12)有3 BOARD,1 BATH,发票12345有两只狗(petid 14和15)有4 BOARD,4 PLAY,1 BATH和4 BOARD,2分别为1个BATH。我的表目前看起来像这样:

  DATE   | NAME | TOTAL | LNAME
---------|------|-------|-------
1/1/2013 | ODIE |   75  | SMITH
1/1/2013 | YODA |  115  | QWERT
1/1/2013 | C3PO |   90  | QWERT

,查询如下所示:

SELECT 
  Invoices.InDate, 
  Pets.PtPetName, 
  SUM([IIQuantity]*[IIEach]) AS Total, 
  Clients.CLLastName
FROM 
  (((Clients INNER JOIN Pets ON Clients.CLSeq = Pets.PtOwnerCode) 
INNER JOIN 
  Invoices ON Clients.CLSeq = Invoices.InClientSeq) 
INNER JOIN 
  InvoiceItems ON (Invoices.InSeq = InvoiceItems.IIInvSeq) 
               AND (Pets.PtSeq = InvoiceItems.IIPetSequence)) 
INNER JOIN 
  Inventory ON InvoiceItems.IIItemCode = Inventory.InvSeq
WHERE (((Invoices.InDate)>#12/31/2012#))
GROUP BY Invoices.InDate, 
  Pets.PtPetName, 
  Clients.CLLastName,
  Invoices.InSeq
ORDER BY  Invoices.InSeq;

我希望这个表以某种方式获得另一个“Items”列,它们将是InvoiceItems.IIItemQuantity和InvoiceItems.IIItemCodeDesc的组合。我一直在寻找各种方法来连接事物,但没有任何东西接近工作(我有一堆内部联接,我不知道我是否需要,或者真的很多关于它是怎么回事。)

1 个答案:

答案 0 :(得分:1)

您可以为此目的定义user defined function(仅举例):

Public Function GetItemList(invoice as Integer) As String
    Dim r As DAO.Recordset
    Dim result As String
    result = ""
    Set r = CurrentDb.OpenRecordset("SELECT Quantity, ItemDesc FROM your_joins WHERE Invoices.InvSeq =" & invoice & ";")
    do until r.EOF
        result = result & CStr(r![Quantity]) & " " & r![ItemDesc] & ", "
        r.MoveNext
    loop
    r.Close
    GetItemList = result
End Function

并在查询中使用它:

select Invoices.invseq, GetItemList(Invoices.InvSeq) as ItemList from Invoices