1

我有看起来像这样的表:

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  |
+------+-------+--------+--------+--------+------+--------+------+--------+

该表仅显示来自特定的数据locationSTATUS READY 是具有相同类型和位置且具有READY状态的单元的累积,等等STATUS STOREDTOTAL是同一类型的总单价/价格Location

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

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

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

我怎样才能做到这一点?

4

0 回答 0