Sql server MAX()SQL Server多行。如何修复每年每月仅返回一行?

Sql server MAX()SQL Server多行。如何修复每年每月仅返回一行?,sql-server,max,Sql Server,Max,我需要帮助正确使用函数MAX,因为当我明确表示需要MAXMonthid时,我似乎得到了不止一行,它应该为客户返回最后一行monthyear 我需要的是客户细分或协议的最后一个月行。当我最终将customer_段和agreement列放入原始列时,当我只需要一行时,我会得到多达6个不同的每月行,它们具有不同的customer_段名称 你如何解决这个问题 --Finding customer segment SELECT a.[cust_no]

我需要帮助正确使用函数MAX,因为当我明确表示需要MAXMonthid时,我似乎得到了不止一行,它应该为客户返回最后一行monthyear

我需要的是客户细分或协议的最后一个月行。当我最终将customer_段和agreement列放入原始列时,当我只需要一行时,我会得到多达6个不同的每月行,它们具有不同的customer_段名称

你如何解决这个问题

--Finding customer segment
    SELECT  
             a.[cust_no]
          ,Customer_Segment
            ,max(monthid) AS monthyear
            INTO #Segment
      FROM Original_table a
      INNER JOIN Customer_Segment ku
        on ku.Cust_no=a.cust_no

    GROUP BY a.cust_no,Customer_Segment
  --------------------------------------------------------------------------
--Finding agreement(yes/no)


  SELECT DISTINCT 
  a.cust_no,
  Agreement,
  max(monthid) as Monthyear
  into #Agreement
  FROM Original_table a
  INNER JOIN Cust_Details zx
    ON zx.cust_no=a.cust_no 

    GROUP BY a.cust_no,
        zx.Agreement
    ------------------------------------------------
-- Attaching columns to original file on cust_no
select DISTINCT 

A.cust_no,
B.Customer_Segment,
d.Agreement

from Original_table A
LEFT JOIN ( SELECT DISTINCT * FROM #Segment ) b
    on b.cust_no=A.cust_no

LEFT JOIN( SELECT  distinct *  FROM #Agreement ) d
    ON d.cust_no=a.cust_no

你是不是遗漏了一些关于连接的信息

(...)
LEFT JOIN ( SELECT DISTINCT * FROM #Segment ) b
    on b.cust_no=A.cust_no and
b.Customer_Segment = A.Customer_Segment

LEFT JOIN( SELECT  distinct *  FROM #Agreement ) d
    ON d.cust_no=a.cust_no and
d.Agreement = A.Agreement
试试这个:

select 
  A.cust_no, b.monthyear,
  e.Customer_Segment,
  d.Agreement    
from Original_table A
JOIN (SELECT a.[cust_no] cust_no ,max(monthid) AS monthyear
      FROM Original_table a) b on b.cust_no=A.cust_no
OUTER APPLY 
( SELECT TOP 1 Agreement FROM Cust_Details d
  WHERE d.cust_no=a.cust_no
  ORDER BY Agreement
) d
OUTER APPLY 
( SELECT TOP 1 Customer_Segment FROM Customer_Segment e 
  WHERE e.cust_no=a.cust_no
  ORDER BY Customer_Segment
) e

我想问题出在分组上。请共享一个sql FIDDLE什么是sql FIDDLE?有人可以帮忙吗?没有,我没有错过任何其他连接。它们之间唯一的共同变量是cust_no。我只在customer_段表上尝试了这一点,并写道:按cust_no,customer_段选择cust_no,customer_段,MAXmonthid as monthyear从cccxc组中选择cust_no,customer_段,我得到双倍。我甚至确保将max变量转换为int。它不起作用,但是如果你有一个以上的客户协议,按客户和协议分组,你当然会得到超过一行。你能提供一些样本数据吗?如果可能,如何检索客户的最后记录?我得到了几行月和客户细分。协议为“是”或“否”。我尝试仅检索客户的最后可用记录。我该怎么写呢?你有没有考虑过使用ROW_uuunumber?你可以像@TabAlleman建议的那样,将ROW_unumber按cust_uno ORDER按monthid desc myOrder划分,然后在连接上筛选myOrder=1。