SQL根据日期显示较少信息

时间:2011-10-18 15:38:28

标签: sql sql-server

我有这个代码,它返回的是一些客户端的列表,但它列出了太多。这是因为它列出了几个与不同日期相同的东西。我只想显示最新的日期而不是其他日期。我尝试通过Client_Code做一个组,但是它不起作用,它只是通过聚合函数或类似的东西(如果需要可以获得)。我被要求得到的是我们所有的客户,列出了所有细节。在'as'部分,他们都正确地通过。如果我拿出来:

I.DATE_LAST_POSTED as 'Last Posted',
I.DATE_LAST_BILLED as 'Last Billed'

它显示正常,但我只需要显示上次结算日期。但是,这些行显示客户几次列出所有不同的账单日期。而且我认为这是因为它跨越了Matter_Master表中不同的事物。从本质上讲,我只想在最后一个账单日期显示最高事项的客户信息。

如果需要澄清,请告诉我,我试着尽力解释......

SELECT DISTINCT
A.DIWOR as 'ID',
B.Client_alpha_Name as 'Client Name',
A.ClientCODE as 'Client Code',
B.Client_address as 'Client Address',
D.COMM_NO AS 'Contact',
E.Contact_full_name as 'Possible Key Contact',
G.LOBSICDESC as 'LOBSIC Code',
H.EARNERNAME as 'Client Care Parnter',
A.CLIENTCODE + '/' + LTRIM(STR(A.LAST_MATTER_NUM)) as 'Last Matter Code',
I.DATE_LAST_POSTED as 'Last Posted',
I.DATE_LAST_BILLED as 'Last Billed'
FROM CLIENT_MASTER A
JOIN CLIENT_INFO B 
ON A.CLIENTCODE=B.CLIENT_CODE
JOIN MATTER_MASTER C
ON A.DIWOR=C.CLIENTDIWOR 
JOIN COMMINFO D
ON A.DIWOR=D.DIWOR
JOIN CONTACT E
ON A.CLIENTCODE=E.CLIENTCODE
JOIN VW_CONTACT F
ON E.NAME_DIWOR=F.NAME_DIWOR    
JOIN LOBSIC_CODES G
ON A.LOBSICDIWOR=G.DIWOR
JOIN STAFF H
ON A.CLIENTCAREPARTNER=H.DIWOR
JOIN MATTER I
ON C.DIWOR=I.MATTER_DIWOR
WHERE F.COMPANY_FLAG='Y'
AND C.MATTER_MANAGER NOT IN ('78','466','2','104','408','73','51','561','504','101','13','534','16','461','531','144','57','365','83','107','502','514','451')  
AND I.DATE_LAST_BILLED > 0
GROUP BY A.ClientCODE
ORDER BY A.DIWOR

2 个答案:

答案 0 :(得分:2)

您的问题是您没有使用足够的聚合函数。这可能是您使用DISTINCT子句 GROUP BY子句的原因(建议使用GROUP BY,而不是DISTINCT )。

所以...删除DISTINCT,将必要的(唯一的,或多或少)列列表添加到GROUP BY子句中,并将其余列包含在聚合函数,常量或子选择中。在想要最大日期的特定情况下,将其包装在MAX()函数中。

答案 1 :(得分:0)

如果我理解得对:

--=======================
-- sample data - simplifed output of your query
--=======================
declare @t table
(
    ClientCode int,
    ClientAddress varchar(50),
    DateLastBilled datetime
    -- the rest of fields is skipped
)

insert into @t values (1, 'address1', '2011-01-01')
insert into @t values (1, 'address1', '2011-01-02')
insert into @t values (1, 'address1', '2011-01-03')
insert into @t values (1, 'address1', '2011-01-04')

insert into @t values (2, 'address2', '2011-01-07')
insert into @t values (2, 'address2', '2011-01-08')
insert into @t values (2, 'address2', '2011-01-09')
insert into @t values (2, 'address2', '2011-01-10')


--=======================
-- solution
--=======================
select distinct
    ClientCode,
    ClientAddress,
    DateLastBilled
from
(
    select 
        ClientCode,
        ClientAddress,
        DateLastBilled,
        -- list of remaining fields
        MaxDateLastBilled = max(DateLastBilled) over(partition by ClientCode)
    from 
    (
        -- here should be your query
        select * from @t
    ) t
) t
where MaxDateLastBilled = DateLastBilled