Sqlserver
 sql >> Teknologi Basis Data >  >> RDS >> Sqlserver

Menemukan nilai bukan nol sebelumnya dari daftar urutan tanggal

Ini tabel contoh Anda

SELECT * INTO #TEMP
FROM
(
SELECT 'Item1' [Item Name],      '01/01/2013' [Date], 10.00 [Price]
UNION ALL
SELECT 'Item1',      '02/01/2013', 9.50
UNION ALL
SELECT 'Item1',      '03/01/2013', 0
UNION ALL
SELECT 'Item1',      '04/01/2013', 7.50
UNION ALL
SELECT 'Item1',     '05/01/2013', 0.00
UNION ALL
SELECT 'Item1',     '06/01/2013', 0.00
UNION ALL
SELECT 'Item1',     '07/01/2013', 11.00
UNION ALL
SELECT 'Item2',      '01/01/2013', 0.00
UNION ALL
SELECT 'Item2',     '02/01/2013', 12.00
UNION ALL
SELECT 'Item2',      '03/01/2013', 0.00
UNION ALL
SELECT 'Item2',      '04/01/2013', 0.00
UNION ALL
SELECT 'Item2',     '05/01/2013', 13.00
)TAB

Dan kueri hasil

 SELECT [Item Name],[Date],
CASE WHEN [Price]=0 THEN 
    ISNULL((SELECT TOP 1 [Price]
     FROM #TEMP T2 
     WHERE CAST(T2.[Date] AS DATE)<T1.[Date] AND T1.[Item Name]=T2.[Item Name] AND T2.[Price]>0
     ORDER BY CAST(T2.[Date] AS DATE) DESC),0) 
    ELSE [Price] END [Price]
FROM #TEMP T1

Hasil Anda ada di sini

Ini adalah Fiddle yang berfungsi http://sqlfiddle.com/#!3/afabd/1 (Jika ini menunjukkan kesalahan saat memuat halaman, tekan RUNSQL, itu akan berhasil)




  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Arsitektur SQL Server AlwaysOn (Availability Group) dan Instalasi Langkah demi Langkah -1

  2. Simpan array di SQL Server 2008

  3. Aliran Bersyarat SQL Server

  4. SQL Server 2008 Data vertikal ke Horizontal

  5. Baris yang dipisahkan koma SQL dengan klausa Group By