根据两个列值获取不同的行

时间:2013-08-20 13:04:44

标签: tsql greatest-n-per-group

我试图从临时表中获取不同的行并将它们输出到aspx页面。我试图使用一列的值,并获得该列中的最后一个条目。

我一直在尝试使用inner joinmax()。但是我没有成功。

以下是我一直尝试使用的代码。

Declare @TempTable table    (
    viewIcon nvarchar(10),
    tenderType nvarchar(20),
    diaryIcon int,
    customerName nvarchar(100),
    projectName nvarchar(100),
    diaryEntry nvarchar(max),
    diaryDate nvarchar(20),
    pid nvarchar(20)

    )

insert into @TempTable(
    viewIcon,
    tenderType,
    diaryIcon,
    customerName,
    projectName,
    diaryEntry ,
    diaryDate ,
    pid 
    )

select p.viewicon, 
    p.[Tender Type],
    1 diaryicon,
    c.[Customer Name],
    co.[Last Project],
    d.Action,
    co.[Diary Date],
    p.PID
    From Projects2 p Inner Join 
(select distinct Pno, max(convert(date,[date of next call],103)) maxdate from ProjectDiary group by Pno
    ) td on  p.PID = td.Pno
Inner Join contacts3 co on co.[Customer Number] = p.[Customer Number]
Inner Join Customers3 c on p.[Customer Number] = c.[Customer Number]
Inner Join ProjectDiary d on td.Pno = d.Pno 
Where CONVERT(Date, co.[Diary Date], 103) BETWEEN GETDATE()-120 AND GETDATE()-60

DECLARE @contactsTable TABLE
    (pid nvarchar(200), 
    diaryDate date)

insert into @contactsTable (t.pid, t.diarydate)
select distinct pid as pid, MAX(CONVERT(DATE, diaryDate, 103)) as diaryDate from @        TempTable t group by pid
DECLARE @tempContacts TABLE
(pid nvarchar(200))

insert into @tempContacts(pid)
select pid from @contactsTable
DECLARE @tempDiaryDate TABLE (diaryDate date)
insert into @tempDiaryDate(diaryDate)
select distinct MAX(CONVERT(DATE, diaryDate, 103)) from @TempTable

select t.* from @TempTable t inner join (select distinct customerName, M    AX(CONVERT(DATE, diaryDate, 103)) AS diaryDate from @TempTable group by customerName) tt on t    t.customerName=t.customerName
where t.pid not in 
(select Pno from ProjectDiary where convert(date,[Date Of Next Call],103) > GETDATE())
and t.viewIcon <> '098'
and t.viewIcon <> '163'
and t.viewIcon <> '119'
and t.pid in (select distinct pid from @tempContacts)
and CONVERT(DATE, t.diaryDate, 103) in (select distinct CONVERT(DATE, diaryDate, 103) f    rom @tempDiaryDate)
order by CONVERT(DATE, tt.diaryDate, 103)

我正在尝试使用最大日期获取所有不同的customerName来确定它使用的记录。

1 个答案:

答案 0 :(得分:1)

使用子查询。不经过整个sql语句,一般的想法是:

 Select [Stuff]
 From table t
 Where date = (Select Max(Date) from table
               where customer = t.customer)