检索具有多行的最小创建日期

时间:2019-03-23 18:13:16

标签: sql sql-server tsql group-by

我尝试编写的SQL查询有问题。我正在尝试检索每个inst(请参见表)和数量(不是唯一的)具有最小create_dt的行。

很遗憾,我不能使用分组依据,因为amount列不是唯一的。

+--------------+--------+------+-------------+
| Company_Name | Amount | inst | Create Date |
+--------------+--------+------+-------------+
| Company A    |   1000 | 4545 | 01/10/2018  |
| Company A    |    400 | 4545 | 01/11/2018  |
| Company A    |    200 | 4545 | 31/10/2018  |
| Company B    |   2000 | 4893 | 01/10/2016  |
| Company B    |    212 | 4893 | 04/10/2016  |
| Company B    |    100 | 4893 | 10/10/2017  |
| Company B    |     20 | 4893 | 04/10/2018  |
+--------------+--------+------+-------------+

在上面的示例中,我希望看到:

+--------------+--------+------+-------------+
| Company_Name | Amount | inst | Create Date |
+--------------+--------+------+-------------+
| Company A    |   1000 | 4545 | 01/10/2018  |
| Company B    |   2000 | 4893 | 01/10/2016  |
+--------------+--------+------+-------------+

代码:

SELECT 
    bill_company, bill_name, account_no 
FROM 
    dbo.customer_information;

SELECT 
    balance_id, balance_id2, minus_balance,new_balance,   
    create_date, account_no
FROM 
    dbo.btr

SELECT
    balance_id, balance_id2, expired_Date, amount, balance_type, account_no
FROM 
    dbo.btr_balance

SELECT 
    balance_ist, expired_date, account_no, balance_type
FROM 
    dbo.BALANCE_inst

检索具有最低余额的实例实例的最小创建数据。

(SELECT  
     bill_company,
     bill_name, 
     account_no, 
     balance_ist, 
     amount,
     MIN(create_date)
 FROM 
     dbo.mtr btr 
 LEFT JOIN
     btr_balance btrb ON btr.balance_id = btrb.balance_id 
                      AND btr.balance_id2 = btrb.balance_id2 
 LEFT JOIN 
     balance_inst bali ON btr.account_no = bali.account_no 
                       AND btrb.expired_date = bali.expired_date  
 GROUP BY 
     bill_company, bill_name, account_no,amount, balance_ist)

我已经看到了一些有关使用关联查询的解决方案,但是看不到解决之道。

2 个答案:

答案 0 :(得分:1)

公用表表达式(CTE)将为您提供帮助。

;with cte as (
   select *, row_number() over(partition by company_name order by create_date) rn
   from dbo.myTable
)
select * from cte
where rn = 1;

答案 1 :(得分:0)

使用row_number(),我假设bill_company是您的公司名称

   select * from 
    ( SELECT  bill_company,
        bill_name, 
        account_no, 
        balance_ist, 
        amount,
        create_date,
        row_number() over(partition by bill_company order by create_date) rn
FROM dbo.mtr btr left join btr_balance btrb 
on btr.balance_id = btrb.balance_id and btr.balance_id2 = btrb.balance_id2 
 left join balance_inst bali 
on btr.account_no = bali.account_no and btrb.expired_date = bali.expired_date
) t where t.rn=1
相关问题