总结每个客户交付的公司(ID)

时间:2017-08-14 14:28:13

标签: sql-server

我回来了;)这次我的任务相当繁重(我想)。

这是我得到的:

|customerID ||company  |compdel |Street  |Code |Date 1     |Date 2     |
+-------------------------------+--------------------------------------+
|1          ||Example1 |DELExam1|ABC Rd.1|4025 |01.01.2015 |01.08.2015 |
|1          ||Example1 |DELExam1|ABC Rd.1|4025 |13.04.2015 |01.12.2015 |
|1          ||Example1 |DELExam2|DEL St.1|0212 |13.03.2015 |09.07.2015 |
|1          ||Example1 |DELExam3|REF Wy.1|9875 |26.05.2015 |16.09.2015 |
|2          ||Example2 |DELExam4|REG St.1|6754 |21.02.2015 |16.05.2015 |
|2          ||Example2 |DELExam5|HIO Wy.1|9999 |01.03.2015 |06.08.2015 |
|2          ||Example2 |DELExam5|HIO Wy.1|9999 |01.01.2015 |06.02.2015 |

我希望为每个客户ID显示每个交付的公司(compdel)在一行中总计日期1中的最早日期和日期2中的最新日期。为了使其更容易理解,我想要这样的结果:

|customerID ||company  |compdel |Street  |Code |Date 1     |Date 2     |
+-------------------------------+--------------------------------------+
|1          ||Example1 |DELExam1|ABC Rd.1|4025 |01.01.2015 |01.12.2015 |
|1          ||Example1 |DELExam2|DEL St.1|0212 |13.03.2015 |09.07.2015 |
|1          ||Example1 |DELExam3|REF Wy.1|9875 |26.05.2015 |16.09.2015 |
|2          ||Example2 |DELExam4|REG St.1|6754 |21.02.2015 |16.05.2015 |
|2          ||Example2 |DELExam5|HIO Wy.1|9999 |01.01.2015 |06.08.2015 |

我已经尝试过这个选择声明,但它不起作用:我知道,这只能是答案的一部分......

SELECT *
FROM 
    (SELECT 
         customerID, company, compdel, Street, Code, Date 1, Date 2, 
         ROW_NUMBER() OVER(PARTITION BY compdel ORDER BY customerID) rn
     FROM 
         table 1) as Y
WHERE 
    rn = 1

1 个答案:

答案 0 :(得分:1)

GROUP BY与不同的值(customerId,公司等)以及MINMAX用于日期

SELECT CustomerId
    , Company
    , CompDel
    , Street
    , Code
    , MIN(Date1) As EarliestDate1
    , MAX(Date2) AS NewestDate2
FROM YourTable
GROUP BY CustomerId, Company, CompDel, Street, Code