根据最大值

时间:2016-07-25 14:44:57

标签: sql sql-server

CREATE TABLE #TmpTbl
(
 PurchaseId INT
,UserID INT
,InvoiceName VARCHAR(20)
,PaymentDue DATE
,PaymentMade DATE
)

INSERT  INTO #TmpTbl
    SELECT  1
           ,1
           ,'Ef Fee'
           ,'2016-01-01'
           ,'2016-01-02'
    UNION ALL
    SELECT  2
           ,1
           ,'Monthly Pmt'
           ,'2016-05-01'
           ,'2016-05-02'
    UNION ALL
    SELECT  3
           ,1
           ,'Ef Fee'
           ,'2016-07-26'
           ,NULL

PurchaseId    UserID    InvoiceName    PaymentDue    PaymentMade
    1           1       EF Fee         2016-01-01    2016-01-02
    2           1       Monthly Pmt    2016-05-01    2016-05-02
    3           1       EF Fee         2016-07-26    NULL

抱歉这个糟糕的标题。
我需要的是为每个用户获取名为MAX(PaymentDue)的发票的Ef Fee。然后我需要根据选择的行获取PaymentMade值(通常是其他一些列)。能够获得行的PurchaseId会很好,但不是必需的。我过去做过这种方式的方法是多次CTE。抓住UserId, InvoiceName, MAX(PaymentDue)然后匹配所有3以获取所需的其他数据,但我想知道是否有更好/更快的方法来完成此操作而无需使用多个cte' s

所需的结果将是第3行,因为它是最新的PaymentDue

编辑:

PurchaseId    UserID    InvoiceName    PaymentDue    PaymentMade
    3           1       EF Fee         2016-07-26    NULL

2 个答案:

答案 0 :(得分:2)

假设我正确理解您的问题,可以使用public DataSet GetDataSet(string sqlCommand, string ConnectionString) { string connectionString = (ConfigurationManager.ConnectionStrings["datConnectionString"].ConnectionString); DataSet ds = new DataSet(); using (SqlCommand cmd = new SqlCommand(sqlCommand, new SqlConnection(connectionString))) { cmd.Connection.Open(); DataTable rollTable = new DataTable(); rollTable.Load(cmd.ExecuteReader()); ds.Tables.Add(rollTable); if (rollTable.Rows.Count > 0) { foreach (DataRow rw in rollTable.Rows) { //Get StartTime in Time format string StaffID = rw["staff_code"].ToString(); if (string.IsNullOrEmpty(StaffID) == true) { //Do nothing } else { string ShortStaffID = StaffID.Substring(2); rw["staff_code"] = ShortStaffID.ToString(); } } //Gets data from datatable and inserts it into table within database string consString = ConfigurationManager.ConnectionStrings["rollPlusConnectionString"].ConnectionString; using (SqlConnection con = new SqlConnection(consString)) { using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con)) { //Set the database table name sqlBulkCopy.DestinationTableName = "dbo.roll"; if (rollTable.Rows.Count > 0) { con.Open(); sqlBulkCopy.WriteToServer(rollTable); con.Close(); } else { } } } } } return ds; } 选择一个选项:

row_number

答案 1 :(得分:0)

另一种不使用CTE或Derived表的方法..

select top 1 with ties 
PurchaseId  ,
  UserID ,
InvoiceName,
 PaymentDue,
 PaymentMade
from
table
order by 
Row_number() over (partition by userid order by purchase due desc)