通過在查詢中使用group by source子句,得到以下結果。Mysql:在組中添加條件
Source No_of_users
1 2
2 7
3 3
4 34
5 21
我怎樣才能像一羣源即輸出的一些值:
Source No_of_users
1+2 9
3+5 24
4 34
需要建議。
通過在查詢中使用group by source子句,得到以下結果。Mysql:在組中添加條件
Source No_of_users
1 2
2 7
3 3
4 34
5 21
我怎樣才能像一羣源即輸出的一些值:
Source No_of_users
1+2 9
3+5 24
4 34
需要建議。
是,使用聯合像:
SELECT SUM(no_of_users) AS some_sum from some_table where source in (1,2,3)
UNION
SELECT SUM(no_of_users) AS some_sum from some_table where source in (4,5,6)
UNION
SELECT SUM(no_of_users) AS some_sum from some_table where source in (6,7,8)
Try This......
with cte as (
select
case Name
when '2' then '1'
when '5' then '3'
//add more combinations ....
else Name
end as Name
from table
)
select Name, count(*)
from cte
group by Name
這可以通過使用一個嵌套SELECT
到Source
柱強制爲適當的值,則分組生成的行來實現:
SELECT Source,
SUM(No_of_users)
FROM (SELECT CASE
WHEN Source = 1 THEN '1+2'
WHEN Source = 2 THEN '1+2'
WHEN Source = 3 THEN '3+5'
WHEN Source = 5 THEN '3+5'
ELSE Source
END AS Source,
No_of_users
FROM `Table`) AS A
GROUP BY Source
SQL提琴可用here來演示。
在MySQL中,你可以這樣做:
SELECT (CASE WHEN Source in (1, 2) THEN '1+2'
WHEN Source in (3, 5) THEN '3+5'
ELSE Source
END) as Source,
SUM(No_of_users) as No_of_users
FROM `Table` t
GROUP BY Source
ORDER BY Source;
什麼是這種 '分組' 的標準是什麼? – Strawberry