根据其他列值划分列值

时间:2016-04-27 16:25:21

标签: mysql sql

我正在尝试衡量一些销售数据随时间的增长。我根据最近n个月对当前和以前的销售进行了分组,得出以下(缩写)表:

+-------------------------------+---------------+-------------+
| CUSTOMER_NAME                 | TIMEFRAME     | GROSS_SALES |
+-------------------------------+---------------+-------------+
| SALLY'S SALES INC             | CURRENT       |     1207.76 |
| SALLY'S SALES INC             | PREVIOUS      |     8139.49 |
| DAVES PRODUCTS LLC            | CURRENT       |      909.92 |
| DAVES PRODUCTS LLC            | PREVIOUS      |     2867.41 |
| MEGACORP                      | CURRENT       |     8369.05 |
| MEGACORP                      | PREVIOUS      |    19123.75 |
+-------------------------------+---------------+-------------+

我正在尝试计算当前和之前销售额之间的商数,例如

+-------------------------------+----------------+
| CUSTOMER_NAME                 | SALES_FACTOR   |
+-------------------------------+----------------+
| SALLY'S SALES INC             | 0.148382761082 |
| DAVES PRODUCTS LLC            | 0.317331668649 |
| MEGACORP                      | 0.690302092999 |
+-------------------------------+----------------+

但是,我无法找出一个正确划分每个客户名称的两个值的查询。

3 个答案:

答案 0 :(得分:0)

使用不同名称的表格两次......

select CUSTOMER_NAME, t1.TIMEFRAME/t2.TIMEFRAME 
  from TABLE_NAME as t1, TABLE_NAME as t2 
 where t1.CUSTOMER_NAME = t2.CUSTOMER_NAME 
   and t1.TIMEFRAME  = 'PREVIOUS' 
   and t2.TIMEFRAME = 'CURRENT'

答案 1 :(得分:0)

一种方法使用条件聚合:

select customer_name,
       (max(case when time_frame = 'Current' then gross_sales end) /
        max(case when time_frame = 'Previous' then gross_sales end)
       ) as ratio
from t
group by customer_name;

答案 2 :(得分:0)

您可以使用GROUP BY为每位客户获取一行,然后SUM(CASE)选择当前和之前的值。

这样做的好处是只扫描一次表,而不需要连接。

SELECT
   CUSTOMER_NAME,
   SUM(CASE WHEN TIMEFRAME = 'CURRENT'  THEN GROSS_SALES END)
   /
   SUM(CASE WHEN TIMEFRAME = 'PREVIOUS' THEN GROSS_SALES END)  AS SALES_FACTOR
FROM
   yourTable
GROUP BY
   CUSTOMER_NAME