2012-07-11 101 views
2

,如果我想打一個查詢,得到用戶分組年齡的計數SQL查詢(按組)

獲得數每年爲單獨:

select count(*) 
from tbl_user 
group by age 

如何我可以做一個自定義組的,所以我可以在例如年齡範圍... 這樣的例子:

group by ages as 0-18 , 19-25 , 26-... 

回答

3

SUM 1和CASE WHEN在MS SQL Server中,工作是否使用的是SQL的版本?

SELECT 
    SUM(CASE WHEN Age >= 0 AND Age <= 18 THEN 1 ELSE 0 END) AS [0-18], 
    SUM(CASE WHEN Age >= 19 AND Age <= 25 THEN 1 ELSE 0 END) AS [19-25] 
FROM 
    YourTable 
5

外部查詢使用子查詢和組CASE表達的表達:

select age_group, count(*) 
from (
    select case when age between 0 and 18 then '0-18' 
       when age between 19 and 26 then '19-25' 
       ... 
       end as age_group 
    from tbl_user 
) t 
group by age_group 
1

你可以使用一個CASE聲明:

SELECT Sum(CASE WHEN age BETWEEN 0 AND 18 THEN 1 ELSE 0 END) as [0-18], 
Sum(CASE WHEN age BETWEEN 19 AND 25 THEN 1 ELSE 0 END) as [19-25], 
Sum(CASE WHEN age BETWEEN 26 AND 34 THEN 1 ELSE 0 END) as [26-34] 
FROM tbl_user 

這將 「扁平化」將數據分成一行 - 爲每個分組獲取一行,將其用作View的基礎,然後從中進行選擇。

1

數據屬於表格,不在代碼中。年齡類別是數據,恕我直言。

CREATE TABLE one 
     (val SERIAL NOT NULL PRIMARY KEY 
     , age INTEGER NOT NULL 
     ); 
INSERT INTO one (age) SELECT generate_series(0,31, 1); 

CREATE TABLE age_category 
     (low INTEGER NOT NULL PRIMARY KEY 
     , high INTEGER NOT NULL 
     , description varchar 
     ); 
INSERT INTO age_category (low,high,description) VALUES 
    (0,19, '0-18') 
, (19,26, '19-25') 
, (26,1111, '26-...') 
     ; 

SELECT ac.description, COUNT(*) 
FROM one o 
JOIN age_category ac ON o.age >= ac.low AND o.age < ac.high 
GROUP BY ac.description 
     ;