获取有史以来第一份合同的类型字段

时间:2018-11-04 05:54:19

标签: sql

我有这样的合同表

CREATE TABLE contracts 
(
    id INT IDENTITY(1,1) PRIMARY KEY,
    contractor_id INT NOT NULL,
    date DATETIME NOT NULL,
    type VARCHAR(50) NULL
)

我想知道有史以来为承包商订立的第一份合同的类型。

我在下面有查询,但无法输入

SELECT contractor_id, MIN(date) AS min_date 
FROM contracts c 
GROUP BY contractor_id 

谢谢您的帮助

2 个答案:

答案 0 :(得分:2)

您在正确的轨道上。您的查询将Contractors表上的contractor_id分组,并选择该承包商的最短日期。

要获取相应的类型,您需要使用多个联接条件将表重新联接到自身上。

;WITH subq AS (
    SELECT 
        contractor_id, MIN(date) AS min_date
    FROM 
        contracts c
    GROUP BY 
        contractor_id
)
SELECT 
    s.contractor_id, c.type
FROM 
    subq s
LEFT JOIN 
    contracts c ON s.contractor_id = c.contractor_id AND s.min_date = c.date

答案 1 :(得分:2)

通常可以使用窗口函数解决此问题:

def shift_image(X, dx, dy):
    X = np.roll(X, dy, axis=0)
    X = np.roll(X, dx, axis=1)
    if dy>0:
        X[:dy, :] = 0
    elif dy<0:
        X[dy:, :] = 0
    if dx>0:
        X[:, :dx] = 0
    elif dx<0:
        X[:, dx:] = 0
    return X

使用正确的索引,关联子查询通常是最快的方法:

SELECT c.*
FROM (SELECT c.*,
             ROW_NUMBER() OVER (PARTITION BY contractor_id ORDER BY date) as seqnum
      FROM contracts c
     ) c 
WHERE seqnum = 1;

适当的索引应位于select c.* from contracts c where c.date = (select min(c2.date) from contracts c2 where c2.contract_id = c.contract_id ); 上。