子查询连接唯一ID来命名麻烦

时间:2019-04-22 01:35:31

标签: sql group-by subquery mysql-workbench

我有两个有问题的表。我正在尝试查找在2018年分配了3名以上雇用的飞行员的姓名。

taxiPilot表

p_id  p_lname  p_fname  p_city  
043   Smith    John     Dayton
044   Doe      Jane     Cincinnati

分配表

p_id  AT_id   HireNo  AssignDate  City
043   BU78    1       11/29/2018  Dayton
044   BU89    2       11/29/2018  Akron

这只是我拥有的数据的简短示例。

我尝试了以下

select p_fname, p_lname
from taxiPilot tp
join assignment a on tp.p_id = a.p_id
where a.p_id IN (Select count(a.p_id)
from assignment
where AssignDate between "01/01/2018" and "12/31/2018"
group by a.p_id
having count(a.p_id) > 3);

这将导致一个空白表

我希望获得以下信息

p_fname  p_lname  count(a.p_id)
Joe      Smith    5

5 个答案:

答案 0 :(得分:1)

在那种情况下,会是这样的(我没有测试):

select p_fname, p_lname, (Select count(a.p_id)
from assignment
where AssignDate between "01/01/2018" and "12/31/2018"
group by a.p_id
having count(a.p_id) > 3)
from taxiPilot tp
join assignment a on tp.p_id = a.p_id
;

答案 1 :(得分:0)

您打算怎么做?

    StreamsBuilder builder = new StreamsBuilder();

    // key value type here is both String for me and update based on cases
    KStream<String, String> source = builder.stream("input-topic");

    source.filter(new Predicate<String, String>() {
        @Override
        public boolean test(String s, String s2) {
            // your filter logic here and s and s2 are key/value from topic
            // In your case, s2 should be type of your json Java object
            return false;
        }
    }).groupBy(new KeyValueMapper<String, String, String>() {
        @Override
        public String apply(String key, String value) {
            // your group by logic
            return null;
        }
    }).count().toStream().to("new topic");

这将重新调谐一个数字(由于计数),但与分配的ID不匹配。

答案 2 :(得分:0)

我认为,如果您强制转换日期,则可以进行简单的汇总。 dbfiddle

select p_fname, p_lname, count(*)
  from taxiPilot tp 

join assignment a 
  on tp.p_id = a.p_id

where a.AssignDate between CAST('2018-01-01' AS DATETIME) 
                       and CAST('2018-12-31' AS DATETIME)
group by p_fname, p_lname
having count(*) > 3

答案 3 :(得分:0)

with paste as (
select 
p_id, count(a.p_id) 
from assignment
group by 1
having count(*) > 3
)

select p_lname,  p_fname, max(HireNo)
from taxiPilot 
where p_id in (select p_id from paste)
group by 1, 2

虽然没有尝试。

答案 4 :(得分:0)

首先,您的想法正确,但是您的子查询并不仅仅与一个飞行员相关。您只是获取了日期之间的所有任务,但与哪个飞行员没有关联。这样一来,所有飞行员的总人数可能会达到273。

相反,您可以在子查询中添加飞行员ID,然后在该子查询之外加入。这样,您就不会尝试拉动所有飞行员。得到合格的人,然后得到名字。

select
      tp.p_fname,
      tp.p_lname,
      PQ.NumHires
   from
      ( select a.p_id, count(*) NumHires
           from Assignment a
           where a.AssignDate between '2018-01-01' and '2018-12-31'
           group by a.p_id 
           having count(*) > 3) PQ
         JOIN taxiPilot tp
            on PQ.p_id = tp.p_id
   order by
      tp.p_lname,
      tp.p_fname