查找没有子查询的最大日期

时间:2017-01-31 05:43:36

标签: sql sql-server subquery max

我有简单的数据库。我想要的是什么。

获取

的所有员工
  1. 50多年
  2. 参与开发10种产品 等等。
  3. 另外

    结果应包含

    1. 员工年龄
    2. 员工的姓名
    3. 产品的姓氏(适用于ProductEmployee.Date日期)
    4. enter image description here

      我写了这个简单的查询:

      SELECT e.Name, e.Age, p.Name
          FROM ProductEmployee pe1
          JOIN Employee e
              ON e.ID = pe1.EmployeeID
          JOIN ProductEmployee pe2
              ON pe2.EmployeeID = e.ID
          JOIN (
              SELECT pe3.EmployeeID, Max(pe3.Date) Date 
                  FROM ProductEmployee pe3
                  GROUP BY pe3.EmployeeID
          )y ON(y.Date = pe1.Date)    
          JOIN Product p
              ON p.ID = pe1.ProductID
          WHERE e.Age > 50
          GROUP BY pe1.EmployeeID, e.Name, e.Age, p.Name
      HAVING Count(DISTINCT pe2.ProductID) > 10
      ORDER BY e.Name
      

      但我有一个问题。这可以写没有子查询吗?用一句话。

2 个答案:

答案 0 :(得分:1)

考虑您的样本表结构,使用以下查询,它将为您提供预期的输出

我使用了row_number,它将不再需要子查询

declare @employee table (id int, name varchar(10),age int);

insert into @employee values (1,'A',50);

insert into @employee values (2,'B',40);

insert into @employee values (3,'C',40);

insert into @employee values (4,'D',60);

declare @product table (id int, name varchar(10));

insert into @product values (1,'P1');

insert into @product values (2,'P2');

insert into @product values (3,'P3');

insert into @product values (4,'P4');


declare @productemployee table (EmployeeID int, ProductID int,[Date] date);

insert into @productemployee values (1,1,'1/30/2017');

insert into @productemployee values (1,2,'1/16/2017');

insert into @productemployee values (2,1,'1/28/2017');

insert into @productemployee values (2,2,'1/30/2017');

insert into @productemployee values (3,2,'1/29/2017');

insert into @productemployee values (3,3,'1/28/2017');

insert into @productemployee values (4,1,'1/28/2017');

insert into @productemployee values (4,3,'1/31/2017');
select t.name,age,t1.name as product_name from (select e.name,e.age,pe.ProductID,pe.Date,ROW_NUMBER() over(partition by ProductID order by date desc) as row_no from @employee e join @productemployee pe 
on e.id = pe.EmployeeID 
join @product p on pe.ProductID = p.id) as t
join
(
select p.id,p.name,count(pe.ProductID) cnt from @productemployee pe
JOIN @product p
        ON p.ID = pe.ProductID
    GROUP BY p.id,p.name
    ) as t1 on t.ProductID = t1.id
WHERE t.Age >= 50 and row_no=1 and t1.cnt >=10
order by t.name

答案 1 :(得分:1)

尝试这样的事情:

json