将行值更改为第一次匹配

时间:2015-11-30 16:47:10

标签: tsql sql-server-2014

有一个表格具有以下结构: (日期,商店,存在,状态)

2012-10-09  Shop1   0   Trial
2012-10-23  Shop1   0   Trial
2012-10-30  Shop1   0   Trial
2012-11-13  Shop1   0   Trial
2012-11-27  Shop1   1   New
2012-12-11  Shop1   0   New
2012-12-18  Shop1   0   New

我需要将其转换为以下结果:

<h2></h2>

算法设置为试用,直到存在列= 1.

还有更多的商店,因此每个商店的日期价值(在我的情况下为2012-11-27)看起来都不是很清晰。有线索吗?

2 个答案:

答案 0 :(得分:0)

如果您不应该按照它们完全在数据库中的方式排序行,那么当您去获取行号时(您需要它来帮助您找到存在1的行之前的所有行) ),然后在使用ROW_NUMBER时使用ORDER BY(SELECT 1)。它会占用表中的行并给出行号。

然后找到存在的第一行1,并将其存储在变量中。然后,您可以将具有行号的临时表与原始表联接,并在下面进行更新。

那应该为你做到的!

SELECT '2012-10-09' AS ShopDate,  'Shop1' AS ShopName,  '0' AS ShopExists,   'Trial' AS ShopStatus  INTO #Shops UNION
SELECT '2012-10-23',  'Shop1',  '0',   'New'    UNION
SELECT '2012-10-30',  'Shop1',  '0',   'New'    UNION
SELECT '2012-11-13',  'Shop1',  '0',   'New'    UNION
SELECT '2012-11-27',  'Shop1',  '1',   'New'    UNION
SELECT '2012-12-11',  'Shop1',  '0',   'New'    UNION
SELECT '2012-12-18',  'Shop1',  '0',   'New'     


SELECT s.*
     , ROW_NUMBER() OVER (ORDER BY (ShopDate)) AS RowNumber
  INTO #temp
  FROM #Shops s

SELECT *
  FROM #temp

DECLARE @RowNumber INT = (SELECT TOP 1 RowNumber FROM #temp WHERE ShopExists = 1 ORDER BY RowNumber ASC)

--SELECT *
UPDATE s  SET ShopStatus = 'Trial'
  FROM #temp t
  JOIN #Shops s
    ON s.ShopDate = t.ShopDate
   AND s.ShopName = t.ShopName
   AND s.ShopExists = t.ShopExists
   AND s.ShopStatus = t.ShopStatus
 WHERE RowNumber < @RowNumber

SELECT *
  FROM #Shops

DROP TABLE #Shops
DROP TABLE #temp

这是最终结果:

ShopDate    ShopName    ShopExists  ShopStatus
2012-10-09  Shop1       0           Trial
2012-10-23  Shop1       0           Trial
2012-10-30  Shop1       0           Trial
2012-11-13  Shop1       0           Trial
2012-11-27  Shop1       1           New
2012-12-11  Shop1       0           New
2012-12-18  Shop1       0           New

答案 1 :(得分:0)

您可以获取所有&#39;新&#39;的列表使用下面的查询在第一个ShopExists日期之前的行。它包括商店首次存在的日期作为最后一栏。您应该能够使用结果相应地更新表格。

select 
    s1.*, s2.FirstExistsDate 
from 
    Shops s1
inner join 
    ( select s.ShopName, MIN(ShopDate) as FirstExistsDate 
      from Shops s
      where ShopExists = 1
      group by s.ShopName
    ) s2 on s1.ShopName = s2.ShopName and s1.ShopDate < s2.FirstExistsDate and s1.ShopStatus = 'New'