年龄范围计算,其中每个国家至少有两个不同年龄的个体

时间:2017-08-12 18:58:32

标签: mysql sql

对于我的数据集,我想创建结果,以便对于那些国家(至少有两个不同的年龄段),我可以总结年龄范围。

CREATE TABLE Employees(
    ID int (3) NOT NULL,
    Name varchar (50) NOT NULL,
    Age int (3) NOT NULL,
    Nationality varchar (50) NOT NULL
);


INSERT INTO Employees 
    (ID, Name, Age, Nationality)
VALUES
    (1, 'CHIN YEN', '19', 'China'),
    (2, 'MIKE PEARL', '21', 'United Kingdom'),
    (3, 'GREEN FIELD', '45', 'Nethernalnds'),
    (4, 'DEWANE PAUL', '57', 'Canada'),
    (5, 'MATTS', '32', 'Australia'),
    (6, 'PLANK OTO', '51', 'France'),
    (7, 'Manish Kumar', '42', 'India'),
    (8, 'Matts', '55', 'USA'),
    (9, 'Mahesh Kumar', '32', 'USA'),
    (10, 'Chin Yen', '21', 'Japan');

我想要做的是:

SELECT Nationality,
       Max(Age) - Min(Age) AS Age_Range
FROM Employees;

2 个答案:

答案 0 :(得分:2)

我认为你只需要一个group by

SELECT Nationality,
       Max(Age) - Min(Age) AS Age_Range
FROM Employees
GROUP BY Nationality;

您可能想要添加HAVING Age_Range > 0

答案 1 :(得分:1)

要构建一个查询,该查询仅返回至少有两个具有明显非零年龄的个体的年龄范围,以下可以接近。

<select id="amount_id">
<!-- removed onclick -->
<option value="" disabled>Amount</option> 
  <option value="0" title="None">0</option>
  <option value="1" title="One Quarter">1/4</option>
  <option value="2" title="One Half">1/2</option>
  <option value="3" title="Three Quarters">3/4</option>
  <option value="4" title="All">100%</option>
</select>
<textarea id="displayTitle"></textarea>
<script>
  document.getElementById("amount_id").addEventListener('change',function(){
     var eTitle = this.options[this.selectedIndex].getAttribute('title');
     document.getElementById("displayTitle").value = eTitle;
  });
</script>

对于任何个人SELECT Nationality, Max(Age) - Min(NULLIF(Age,0)) AS Age_Range FROM Employees GROUP BY Nationality having Max(Age) - Min(NULLIF(Age,0)) > 0 age=0将其年龄转换为nullif,然后被汇总函数NULL忽略,该怎么办?

我已更改您分享的数据,如下所示。

MIN

以下是使用我共享的查询预期的结果。

enter image description here

您可以查看DEMO here