对于航行(年份,船舶),如何在标准SQL或MS-ACCESS中按年龄间隔对水手进行分组和统计?
YEAR SHIP SAILOR_AGE
2003 Flying dolphin 33
2003 Flying dolphin 33
2003 Flying dolphin 34
2001 Flying dolphin 23
2003 Flying dolphin 35
2001 Flying dolphin 38
2001 Flying dolphin 31
2003 Flying dolphin 36
2003 Columbine 41
2003 Columbine 42
2003 Flying dolphin 27
2003 Flying dolphin 51
2003 Flying dolphin 46
我尝试了什么:
SELECT YEAR, SHIP, SAILOR_AGE, COUNT (*) as `NUMBERS`
FROM TABLE
GROUP BY YEARS, SHIP, SAILOR_AGE;
它给了我每年的水手数量:
示例:
YEAR |SHIP |SAILOR_AGE | NUMBERS
------------------------------------------
2003 | Flying dolphin| 33 | 2
小组水手如何按时间间隔分组
示例:
From 20th to 40th year's old
From 40th to 60th year's old
答案 0 :(得分:2)
您可以尝试使用id
指定以下年龄范围:
CASE
答案 1 :(得分:2)
如果您想要列中的值,可以使用条件聚合:
SELECT YEAR, SHIP, COUNT(*) as NUMSAILORS,
SUM(CASE WHEN SAILOR_AGE BETWEEN 21 AND 40 THEN 1 ELSE 0 END) as AGE_21_40,
SUM(CASE WHEN SAILOR_AGE BETWEEN 41 AND 60 THEN 1 ELSE 0 END) as AGE_41_60
FROM TABLE
GROUP BY YEARS, SHIP;
答案 2 :(得分:2)
由于这个 - 给定标签 - 很可能是Access SQL,你可以这样:
SELECT
YEAR,
SHIP,
INT(SAILOR_AGE / 20) * 20 AS AgeGroup,
COUNT(*) As [NUMBERS]
FROM
TABLE
GROUP BY
YEAR,
SHIP,
INT(SAILOR_AGE / 20) * 20
答案 3 :(得分:1)
您可以使用CASE EXPRESSION
进行单个查询:
SELECT t.years,t.ship,
CASE WHEN t.Sailor_age between 21 and 40 then 'From 20th to 40th'
WHEN t.Sailor_age between 41 and 60 then 'From 40th to 60th'
ELSE 'Other Ages'
END as Range
FROM YourTable t
GROUP BY t.years,t.ship,CASE WHEN t.Sailor_age between 21 and 40 then 'From 20th to 40th' WHEN t.Sailor_age between 41 and 60 then 'From 40th to 60th' ELSE 'Other Ages' END
ORDER BY t.years,t.ship,Range
或者如果您希望使用条件聚合将其作为单行:
SELECT t.years,t.ship,
COUNT(CASE WHEN t.Sailor_age between 21 and 40 then 1 end) as Age_21_to_40,
COUNT(CASE WHEN t.Sailor_age between 41 and 60 then 1 end) as Age_41_to_60,
FROM YourTable t
GROUP BY t.years,t.ship
ORDER BY t.years,t.ship
答案 4 :(得分:1)
我想说实现这一目标的最佳方法是创建帮助表:
DECLARE @hlptbl TABLE(DescOfGrp VARCHAR(50), AgeFrom INT, AgeTo INT)
INSERT INTO @hlptbl (DescOfGrp, AgeFrom, AgeTo)
VALUES('20 to 40', 20, 40),
('41 to 60', 40, 60)
然后,您必须以这种方式加入数据:
SELECT t1.[Year], t1.SHIP, t2.DescOfGrp, COUNT(t1.SHIP) AS Number
FROM TableA As t1 INNER JOIN @hlptbl AS t2 ON
t1.SAILOR_AGE>=t2.AgeFrom AND t1.SAILOR_AGE <=t2.AgeTo
GROUP BY t1.[Year], t1.SHIP, t2.DescOfGrp
结果:
Year SHIP DescOfGrp Number
2001 Flying dolphin 20 to 40 3
2003 Columbine 41 to 60 2
2003 Flying dolphin 20 to 40 6
2003 Flying dolphin 41 to 60 2