我如何Transpose Table或Create Pivote表

时间:2017-01-23 21:34:21

标签: mysql sql pivot-table

我有以下信息,我想创建一个数据透视表客户名称和总和金额。

Customer ID   Customer Bill Name  Item ID  Transaction Date  Amount ...
Cust 1          Customer 1         123       '2017-03-03'     2
Cust 1          Customer 1         123       '2017-02-03'     3
Cust 3          Customer 3         235       '2017-01-03'     4
Cust 3          Customer 3         235       '2017-01-03'     4

我想完成

Customer ID   Customer Bill Name  Item ID  JAN   FEB  MARCH ...
Cust 1          Customer 1         123      2     3    0
Cust 3          Customer 3         235      8     0    0

我有以下代码从表

生成记录
SELECT Customers.CustomerID, Customers.Customer_Bill_Name, Customers.WhichShipVia, GROUP_CONCAT(DISTINCT LineItem.ItemID) AS ItemIDgroup, JrnlHdr.INV_POSOOrderNumber, JrnlHdr.CustomerInvoiceNo, JrnlHdr.Comment2, JrnlHdr.ShipByDate, JrnlHdr.GoodThruDate, JrnlHdr.CustomerSONo, JrnlHdr.Reference, JrnlHdr.TransactionDate, JrnlRow.DistNumber, JrnlRow.Quantity, LineItem.ItemID, LineItem.SalesDescription, LineItem.PartNumber, LineItem.Category, LineItem.ItemClass, LineItem.ItemDescription 
FROM   Customers
INNER JOIN JrnlHdr
ON Customers.CustomerRecordNumber = JrnlHdr.CustVendId
INNER JOIN JrnlRow
ON JrnlHdr.PostOrder = JrnlRow.PostOrder

INNER JOIN LineItem 
ON JrnlRow.ItemRecordNumber = LineItem.ItemRecordNumber

WHERE  JrnlHdr.TransactionDate>='2016-01-01' AND JrnlHdr.JrnlKey_Journal = 3 AND JrnlHdr.PostOrder = JrnlRow.PostOrder  AND JrnlHdr.CustVendId = Customers.CustomerRecordNumber AND JrnlRow.ItemRecordNumber = LineItem.ItemRecordNumber GROUP BY LineItem.ItemID

0 个答案:

没有答案