左连接来自相同源字段和表的某些字段但在MySQL中具有不同的条件

时间:2013-01-01 08:33:50

标签: mysql

我的表格看起来像这样:

ProductList
+------+----------------+--------------+----------+--------+-------+
|  id  | product_number | product_type | location | status | price |
+------+----------------+--------------+----------+--------+-------+
|  1   | A-01           | A001         | Nevada   | READY  | 5000  |
|  2   | B-02           | A002         | Texas    | STORED | 6000  |
|  3   | A-01           | A002         | Utah     | READY  | 6000  |
|  4   | A-02           | B003         | Utah     | READY  | 8000  |
|  5   | B-01           | A001         | Nevada   | STORED | 5000  |
+------+----------------+--------------+----------+--------+-------+

id是主键。

Supervisor
+------+-------+--------------+----------+-----------+--------+
|  id  | month | product_type | location | unit_sold | income |
+------+-------+--------------+----------+-----------+--------+
|  1   | 1     | A001         | Nevada   | 5         | 25000  |
|  2   | 3     | A002         | Texas    | 6         | 36000  |
|  3   | 1     | A002         | Utah     | NULL      | NULL   |
|  4   | 4     | B003         | Utah     | 4         | 32000  |
|  5   | 2     | A001         | Nevada   | 6         | 30000  |
+------+-------+--------------+----------+-----------+--------+

我被问到结果应该像这张表(这实际上是我的估计):

SalesTarget table

Location : Nevada

+------+----------------+--------+--------+---------------+---------------+
|      |     STATUS     |      TOTAL      |   1st MONTH   |   2nd MONTH   |
| TYPE | READY | STORED |  UNIT  | PRICE  | UNIT | INCOME | UNIT | INCOME |
+------+-------+--------+--------+--------+------+--------+------+--------+
| A001 |   6   |    8   |  14    |  70000 |  5   | 25000  |  6   | 30000  |
| A002 |   7   |    4   |  11    |  66000 |  3   | 39000  |  0   |   0    |
| B001 |   3   |    6   |  19    |  95000 |  0   |   0    |  0   |   0    |
| B002 |   5   |    5   |  10    | 100000 |  4   | 40000  |  6   | 60000  |
+------+-------+--------+--------+--------+------+--------+------+--------+

该表仅显示来自特定location的数据。 STATUS READY是具有 READY 状态的相同类型和位置的单位累积,因此STATUS STORED也是如此。 TOTALLocation中相同类型的总单位/价格。

SalesTarget表中的单位和收入可以为NULL,并且将由用户输入,但它们按Supervisor.month分类(并且也是第12个月)。 我通过product_type加入了表(ProductList和Supervisor)。

我尝试使用这样的预处理语句查询命令,但它没有给出我想要的确切结果。

SELECT

pl.product_type AS TYPE,
SUM(IF(pl.status = ? , 1, 0)) AS READY,
SUM(IF(pl.status = ? , 1, 0)) AS STORED,
SUM((IF((pl.status = ? OR pl.status = ? ), 1, 0))) AS UNIT_TOTAL,
SUM((IF((pl.status = ? OR pl.status = ? ), pl.price, 0))) AS PRICE_TOTAL,
IF(sv.month=1, sv.unit_sold, 0) AS UNIT1,
IF(sv.month=1, sv.income, 0) AS INCOME1,
IF(sv.month=2, sv.unit_sold, 0) AS UNIT2,
IF(sv.month=2, sv.income, 0) AS INCOME2

FROM ProductList pl
LEFT OUTER JOIN Supervisor sv ON pl.product_type = sv.product_type
WHERE pl.location = ?
GROUP BY pl.product_type
ORDER BY TYPE DESC

我该怎么做?

0 个答案:

没有答案