sql >> Databasteknik >  >> Database Tools >> SSMS

Hur hämtar man data från SQL Server baserat på nedanstående exempel?

Kanske kan du använda en lösning som nedanSe fungerande demo

declare @d date='2018-Jun-03'

; with Indexer as 
(
    select 
        *, 
        rn= row_number() over(partition by CustName order by RecordedTime),
        rn2=row_number() over(partition by CustName order by RecordedTime desc)
    from records
)
,GetValidCustomerRecords as
(
    select 
        CustName,
        Country,
        RecordedTime,
        Audit   = case when cast(RecordedTime as date)[email protected] and rn=1 then 'add' else 'change' end,
        History = case 
                    when cast(RecordedTime as date)[email protected] and rn=1 
                    then 'new' 
                    when cast(RecordedTime as date)<@d and rn=1 
                    then 'before'
                    else 'current' end
    from Indexer i 
    where CustName in
    (
    select 
        distinct CustName 
    from records
    where cast(RecordedTime as date)[email protected]
    ) 
    and (rn=1 or rn2=1) and cast(RecordedTime as date)<[email protected]
)

select * from GetValidCustomerRecords
order by CustName, RecordedTime



  1. PMA Database ... inte OK i phpMyAdmin uppgradering

  2. För många parametervärden saktar ner frågan

  3. Åtkomst till det begärda objektet är endast tillgängligt från det lokala nätverket phpmyadmin

  4. Hur man löser Microsoft SQL Server. Fel 233. Leverantör:SSL-leverantör