我被要求创建一个报告,显示单个成员的交易数据并显示他们多久进行一次相同类型的交易。基于交易次数的MySql数据透视表
例如:
鲍勃从组织X购买5个香蕉同时对10 不同场合/交易和Bob从同一组织 已上20个不同的 场合/交易购买3个香蕉一次。
数据库包含的交易数据以这种形式
|TransactionID | Organization | MemberNumber | ItemID| QuantityPurchased
我现在有,在下面的格式创建一个临时表的查询。
|Organization | MemberNumber | ItemID | QuantityItemsPurchased | QuantityOfTransactions
----------------------------------------------------------------------------------------
|Company X | 2044 | B2 | 5 | 10
|Company X | 2044 | B2 | 3 | 20
|Company Y | 2035 | A3 | 5 | 5
我被要求创建以下格式(报告的格式不为我的辩论),其中每个数列是交易与销售的项目的是数量和价值的报告每一行是销售该项目数量的交易数量。
|Organization | MemberNumber | ItemID |1 |2 |3 |4 |5 |6+ |
-----------------------------------------------------------------
|Company X | 2044 | B2 |0 |0 |20 |0 |10 |0 |
|Company Y | 2035 | A3 |0 |0 |0 |0 |5 |0 |
我不知道如何编写一个查询,可以进行排序quantityOfItemsPurchased成单独列,显示QuantityOfTransactions值。
我试着写了一个类似于下面的查询,但它不适用于我,因为它只给出所有数字列下的值1或0,而不是实际的QuantityOfTransactions值。
Select Organization, MemberNumber, ItemId,
count(Case when tempTable.quantityOfItemsPurchased = 1 then tempTable.QuantityOfTransactions end) as '1',
count(Case when tempTable.quantityOfItemsPurchased = 2 then tempTable.QuantityOfTransactions end) as '2',
count(Case when tempTable.quantityOfItemsPurchased = 3 then tempTable.QuantityOfTransactions end) as '3',
count(Case when tempTable.quantityOfItemsPurchased = 4 then tempTable.QuantityOfTransactions end) as '4',
count(Case when tempTable.quantityOfItemsPurchased = 5 then tempTable.QuantityOfTransactions end) as '5',
count(Case when tempTable.quantityOfItemsPurchased >= 6 then tempTable.QuantityOfTransactions end) as '6+'
from TempTable group by Organization, MemberNumber, ItemId
这种事情是在应用程序代码中那么容易。 :-( – Strawberry
草莓,同意这样会更容易一些,但我们试图将这些报告与应用程序分开,因为销售/管理总是要求修改报告,而且不得不不断地发布新版本每次发生这种情况,不幸的是我的数据库知识是有限的,但它是这样的, – Jcross