SQL查询根据另一个值中的值替换列的值

时间:2014-03-31 08:34:04

标签: sql sql-server

我在SQL Server中有一个表,其数据如下:

Costing_ID CostingName CostingNumber CostingNumberSuffix StartDate
1          Test        1234                              2014-04-01
2          Test 2      1234          AA                  2014-04-06
3          Test 3      5668                              2014-04-09
4          Test 4      1234          AB                  2014-04-14

我需要生成一个返回所有行的视图,但是将CostingNumberSuffix不为空的项的StartDate替换为相应的CostingNumber的StartDate为空。

所以我的查询应该返回以下内容:

   Costing_ID CostingName CostingNumber CostingNumberSuffix StartDate
    1          Test        1234                              2014-04-01
    2          Test 2      1234          AA                  2014-04-01
    3          Test 3      5668                              2014-04-09
    4          Test 4      1234          AB                  2014-04-01

我该怎么做呢?

4 个答案:

答案 0 :(得分:1)

请尝试此查询。我没有测试过,但你明白了这个想法:

SELECT
    Costing_ID,
    CostingName,
    CostingNumber,
    CostingNumberSuffix,
    CASE
        WHEN CostingNumberSuffix != ''
            THEN (SELECT s.StartDate FROM table s WHERE s.CostingNumber = t.CostNumber and s.CostNumberSuffix = '')
        ELSE
            StartDate
    END 
FROM table t

答案 1 :(得分:1)

SQL Server 2012:

select Costing_ID, CostingName, CostingNumber, CostingNumberSuffix,
first_value(StartDate) over (partition by CostingNumber order by CostingNumberSuffix
    rows unbounded preceding) as StartDate
from Costing
order by Costing_ID

答案 2 :(得分:0)

此解决方案使用公用表表达式(A.k.a CTE)。 CTE找到CostingNumberSuffix为空的项目的StartDate。

WITH CTE AS
(
    SELECT CostingNumber, StartDate
    FROM <tablename>
    WHERE CostingNumberSuffix IS NULL
)
SELECT
    T.Costing_ID,
    T.CostingName,
    T.CostingNumber,
    T.CostingNumberSuffix,
    ISNULL(CTE.StartDate, T.StartDate) AS StartDate
FROM <tablename> T
LEFT OUTER JOIN CTE
ON T.CostingNumber = CTE.CostingNumber

答案 3 :(得分:-1)

以下是基于另一个值中的值替换列值的SQL查询:

select t1.Costing_ID, t1.CostingName, t1.CostingNumber,
  t1.CostingNumberSuffix,
  coalesce (t2.StartDate, t1.StartDate)
from <table name> t1
left join (select * from <table name> where CostingNumberSuffix = '') t2
on t1.costingnumber = t2.costingnumber