按多个聚合列进行分区

时间:2014-04-04 11:05:38

标签: sql sql-server

请参阅下面的DDL:

CREATE TABLE Test (SupplierID int, CustomerID int, SupplierDate datetime, TestColumn1 varchar(10), TestColumn2 varchar(10))
INSERT INTO Test values (1,1, '2010-01-01', 'Apple', 'Banana')
INSERT INTO Test values (1,2, '2006-01-01', 'Pear', 'Grape')
INSERT INTO Test values (2,1, '2004-01-01', 'Carrot', 'Pea')
INSERT INTO Test values (2,2, '2004-01-01', 'Monday', 'Friday')

请参阅下面的SQL:

select SupplierID, CustomerID, Max(SupplierDate) over (partition by SupplierID), TestColumn1, TestColumn2 from test

预期的结果是:

1   1   2010-01-01 00:00:00.000 Apple   Banana
1   2   2010-01-01 00:00:00.000 Pear    Grape
2   1   2004-01-01 00:00:00.000 Carrot  Pea
2   2   2004-01-01 00:00:00.000 Monday  Friday

我想要一个结果:

1   1   2010-01-01 00:00:00.000 Apple   Banana
2   1   2010-01-01 00:00:00.000 Apple   Banana
2   2   2006-01-01 00:00:00.000 Carrot  Pea
1   2   2006-01-01 00:00:00.000 Carrot  Pea

即。 Testcolumn1和TestColumn2需要包含在聚合中。有没有一种简单的方法来实现分区?我之前从未使用过分区。

查询应获取最大供应商日期,然后返回表的供应商ID的每一行的最大供应商日期加测试列1和测试列2。

查询需要返回表中的每一行。

2 个答案:

答案 0 :(得分:1)

试试这个,

;With CTE as 
(
select SupplierID
    , CustomerID
    , Max(SupplierDate) over (partition by CustomerID) as SupplierDate
    , TestColumn1
    , TestColumn2 
from test
)
Select a.SupplierID,a.CustomerID,a.SupplierDate,b.TestColumn1,b.TestColumn2 from CTE as a
inner join Test as b on a.SupplierDate = b.SupplierDate
    and a.CustomerID = b.CustomerID

第二种方法,

select a.SupplierID,a.CustomerID,a.SupplierDate,b.TestColumn1,b.TestColumn2  from Test as a
outer apply
    (
        select top 1  * from Test 
        where Test.CustomerID = a.CustomerID
        order by SupplierDate desc
    )as b
order by a. CustomerID

答案 1 :(得分:1)

完成没有加入

;WITH x as
(
  SELECT SupplierID, CustomerID, SupplierDate,
   CASE WHEN row_number() over (partition by SupplierID order by SupplierDate, 
             customerid desc) = count(*) over (partition by SupplierID) 
     then '' end z,
  TestColumn1, TestColumn2 
  FROM test
)
SELECT SupplierID, CustomerID, 
MAX(SupplierDate) over (partition by SupplierID) SupplierDate,
MAX(TestColumn1 + z) over (partition by SupplierID) TestColumn1,
MAX(TestColumn2 + z) over (partition by SupplierID) TestColumn2
FROM x

结果:

SupplierID  CustomerID      SupplierDate    TestColumn1     TestColumn2
1           2               2010-01-01      Apple           Banana
1           1               2010-01-01      Apple           Banana
2           2               2004-01-01      Carrot          Pea
2           1               2004-01-01      Carrot          Pea