2016-08-15 103 views
1

数据库:任何人都可以帮我约SQL查询(群里)

订单:

| orders_id | shop_id |mode| 
|:-----------|------------:|---:| 
| 1   |  1001 | 1| 
| 2   |  1001 | 1| 
| 3   |  1001 | 2| 
| 4   |  1003 | 1| 
| 5   |  1004 | 1| 
| 6   |  1004 | 2| 

显示:总= total_mode_1 * 20 + total_mode_2 * 10;

| shop_id |total Mode 1|total Mode 2|total| 
|:-----------|-----------:|-----------:|----:| 
| 1001  |   2|   1| 50| 
| 1004  |   1|   1| 30| 
| 1003  |   1|   0| 20| 

我有数据结构。你可以查询这个吗?我尝试了一些时间,但没有工作。 非常感谢!基于

回答

1

这是根据您所提供的公式查询,

select shop_id, 
    count(case when o_mode = 1 then 1 end) as tm_1, 
    count(case when o_mode = 2 then 1 end) as tm_2, 
    count(case when o_mode = 1 then 1 end)*20 + count(case when o_mode = 2 then 1 end)*10 as total 
from order_test 
group by shop_id 
order by total desc; 

结果:

+---------+------+------+-------+ 
| shop_id | tm_1 | tm_2 | total | 
+---------+------+------+-------+ 
| 1001 | 2 | 1 | 50 | 
| 1004 | 1 | 1 | 30 | 
| 1003 | 1 | 0 | 20 | 
+---------+------+------+-------+ 
3 rows in set (0.00 sec) 

您可以在order by条款适用ascdesc,根据您的需要。很显然,查询存在冗余。但我认为我们不能摆脱它,因为更名列不能在select中使用。

注意:o_mode = mode。我刚更名了专栏。

+0

谢谢你的男人。它对我有用:) – Phongdatgl

3

在MySQL更容易,当你使用局部变量:

SELECT 
    shop_id, 
    SUM(@tm1 := IF(`mode`=1, 1, 0)) AS tot_mode_1, 
    SUM(@tm2 := IF(`mode`=2, 1, 0)) AS tot_mode_2, 
    SUM(@tm1 * 20 + @tm2 * 10) AS total 
FROM orders 
GROUP BY shop_id 
ORDER BY total desc 

我们做的是检查,如果模式是1个或2,店里局部变量的每一行,这个局部变量,我们以后需要算总

结果将是:

shop_id  tot_mode_1 tot_mode_2 total 
1001  2   1   50 
1004  1   1   30 
1003  1   0   20 
相关问题