我有一个结算表,其中包含PurchaseDate,ItemType,ItemSize和其他详细信息。
结算表
+--------------------------------------------+
| PurchaseDate | ItemType | ItemSize | price |
+--------------------------------------------+
| 1-Jan-2015 | Jumper | S | 20 |
| 1-Jan-2015 | Jumper | S | 20 |
| 1-Jan-2015 | Jumper | M | 20 |
| 1-Jan-2015 | Jumper | L | 20 |
| 1-Jan-2015 | Shirt | M | 15 |
| 1-Jan-2015 | Shirt | M | 15 |
| 2-Jan-2015 | Shirt | L | 20 |
+--------------------------------------------+
...
ItemType是固定的,可以是Jumper或Shirt。 ItemSize是固定的,可以是S,M或L.
我需要的是显示订购商品的摘要 PurchaseDate,然后是存在的每个组合的计数 每个日期。
示例输出
+----------------------------------------------------------------------------------+
| Date | Jumper[S] | Jumper[M] | Jumper[L] | Shirt[S] | Shirt[M] | Shirt[L] |
+----------------------------------------------------------------------------------+
| 1-Jan-2015 | 2 | 1 | 1 | 0 | 1 | 0 |
| 2-Jan-2015 | 1 | 5 | 0 | 1 | 3 | 3 |
| 3-Jan-2015 | 0 | 0 | 0 | 0 | 0 | 0 |
| 4-Jan-2015 | 0 | 3 | 1 | 1 | 2 | 2 |
+----------------------------------------------------------------------------------+
这是否可以使用mysql查询?
答案 0 :(得分:1)
是的,这是可能的。
select PurchaseDate,
sum(if(ItemType="Jumper" AND ItemSize="S",1,0)) as "Jumper[S]",
sum(if(ItemType="Jumper" AND ItemSize="M",1,0)) as "Jumper[M]",
sum(if(ItemType="Jumper" AND ItemSize="L",1,0)) as "Jumper[L]",
sum(if(ItemType="Shirt" AND ItemSize="S",1,0)) as "Shirt[S]",
sum(if(ItemType="Shirt" AND ItemSize="M",1,0)) as "Shirt[M]",
sum(if(ItemType="Shirt" AND ItemSize="L",1,0)) as "Shirt[L]"
from TableName
group by PurchaseDate;
案例:如果您需要一个月的所有日期,请创建一个包含所有日期的列的表。让表的名称为“datetable”,列名为“datecolumn。
select t1.datecolumn,
sum(if(ItemType="Jumper" AND ItemSize="S",1,0)) as "Jumper[S]",
sum(if(ItemType="Jumper" AND ItemSize="M",1,0)) as "Jumper[M]",
sum(if(ItemType="Jumper" AND ItemSize="L",1,0)) as "Jumper[L]",
sum(if(ItemType="Shirt" AND ItemSize="S",1,0)) as "Shirt[S]",
sum(if(ItemType="Shirt" AND ItemSize="M",1,0)) as "Shirt[M]",
sum(if(ItemType="Shirt" AND ItemSize="L",1,0)) as "Shirt[L]"
from datetable t1 left join TableName t2 on ( date(t1.datecolumn)=date(t2.PurchaseDate))
Where date(t1.datecolumn) between <date_1> and <date_2> // optional if you want data between two dates
group by t1.datecolumn;
注意:代码未经过测试。如果发现任何语法错误,请告诉我。