如何在mysql的where条件中将列值作为变量

时间:2017-11-09 18:29:51

标签: mysql sql

我有一个名为Transactions的表,其中包含transaction_id,prod_subcat_code等列。在where子句中,我给出了两个条件。但我没有得到理想的结果。

Select prod_subcat_code, 
(select count(transaction_id) from Transactions where Qty>'0' and 
prod_subcat_code='1')*100/(select count(transaction_id) from Transactions) 
as Sales_Percentage,
(select count(transaction_id) from Transactions where Qty<'0' and 
prod_subcat_code ='1')*100/(select count(transaction_id) from Transactions) 
as Returns_Percentage from Transactions group by prod_subcat_code;
+------------------+------------------+--------------------+
| prod_subcat_code | Sales_Percentage | Returns_Percentage |
+------------------+------------------+--------------------+
|                1 |          11.5063 |             1.2881 |
|                2 |          11.5063 |             1.2881 |
|                3 |          11.5063 |             1.2881 |
|                4 |          11.5063 |             1.2881 |
|                5 |          11.5063 |             1.2881 |
|                6 |          11.5063 |             1.2881 |
|                7 |          11.5063 |             1.2881 |
|                8 |          11.5063 |             1.2881 |
|                9 |          11.5063 |             1.2881 |
|               10 |          11.5063 |             1.2881 |
|               11 |          11.5063 |             1.2881 |
|               12 |          11.5063 |             1.2881 |
+------------------+------------------+--------------------+
12 rows in set (0.04 sec)

我希望能够找到每个prod_subcat_code的销售和退货百分比,因为我想要一些方法,我可以将prod_subcat_code作为where子句中的变量,以便它可以采用与prod_subcat_code列相同的值。截至目前,我给出的值为1,因此显示第一行的正确结果,但下一行也获得相同的值。有没有办法进行行方式更新,以便prod_subcat_code每行增加1个值。

1 个答案:

答案 0 :(得分:1)

要回答您的问题,您需要为外部查询使用表别名。然后子查询可以引用该表别名,并成为相关子查询。

SELECT prod_subcat_code, 
 (SELECT COUNT(transaction_id) FROM Transactions 
  WHERE Qty>'0' AND prod_subcat_code=t.prod_subcat_code) * 100 / 
 (SELECT COUNT(transaction_id) FROM Transactions) 
  AS Sales_Percentage,
 (SELECT COUNT(transaction_id) FROM Transactions 
  WHERE Qty<'0' AND prod_subcat_code=t.prod_subcat_code) * 100 / 
 (SELECT COUNT(transaction_id) FROM Transactions) 
  AS Returns_Percentage 
FROM Transactions AS t
GROUP BY t.prod_subcat_code;

但它可能比这更简单。如果只使用表达式而不是子查询,则不需要将任何WHERE子句限制为匹配组的行。他们已经凭借GROUP BY限制在该群体中。

Select prod_subcat_code, 
 SUM(CASE WHEN Qty>0 THEN 1 END) * 100 / (SELECT COUNT(*) FROM Transactions) AS Sales_Percentage,
 SUM(CASE WHEN Qty<0 THEN 1 END) * 100 / (SELECT COUNT(*) FROM Transactions) AS Returns_Percentage
FROM Transactions
GROUP BY prod_subcat_code;