将0插入具有相同字段值的连续行

时间:2012-05-23 14:24:07

标签: sql sql-server sql-server-2008 tsql sql-server-2005

我有一个包含以下行的表:

enter image description here

我想创建一个显示以下结果的视图(不更改原始表格):

enter image description here

对于每个具有相同ID,日,月和年的行,我想留下一行包含成本和计数,并在其他行中插入0。

4 个答案:

答案 0 :(得分:2)

您可以这样做:

SELECT id, day, month, year,
  CASE WHEN nNum = 1 then cost else 0 end as cost,
  CASE WHEN nNum = 1 then "Count" else 0 end as "Count",
  datetimeIN, datetimeOUT
FROM (
  SELECT id, day, month, year,
    cost, "Count", datetimeIN, datetimeOUT,
    row_number() OVER (PARTITION BY id, day, month, year
                       ORDER BY datetimeIN) as nNum
  FROM TableName
) A

它使用row_number()对行进行编号,然后使用CASE语句来挑出第一个并使其行为不同。

<强> See it working on SQL Fiddle here.

答案 1 :(得分:2)

这是一种不需要PARTITION的便携式方法。我假设您对组中的多行没有相同的datetimeIN值:

select t.id, t.day, t.month, t.year,
    case when tm.id is null then 0 else t.cost end as cost,
    case when tm.id is null then 0 else t.Count end as Count,
    t.datetimeIN, t.datetimeOUT
from MyTable t
left outer join (
    select id, day, month, year, min(datetimeIN) as minIN
    from MyTable
    group by id, day, month, year
) tm on t.id = tm.id
    and t.day = tm.day
    and t.month = tm.month
    and t.year = tm.year
    and t.datetimeIN = tm.minIN

答案 2 :(得分:0)

或使用公用表表达式:

    with    commonTableExp ([day], [month], [year], minDate) as (
            select  [day], [month], [year], min(datetimeIn)
            from    #temp
            group by [day], [month], [year])
    select  id,
            dt.[day],
            dt.[month],
            dt.[year],
            case when datetimein = minDate then [cost] else 0 end,
            case when datetimein = minDate then [count] else 0 end,
            dateTimeIn
    from    #temp dt join commonTableExp cte on 
                dt.[day] = cte.[day] and
                dt.[month] = cte.[month] and
                dt.[year] = cte.[year]
    order by dateTimeIn

答案 3 :(得分:-2)

查询

Select id, [day], [month], [year], Case When K.RowID = 1 Then [cost] Else 0 End as Cost, Case When K.RowID = 1 Then [count] Else 0 End as [count], [DateTimeIN], [DateTimeOut] From
(
    select ROW_NUMBER() Over(Partition by id, [day], [month], [year] Order by ID ) as RowID, * From Testing
)K

Drop table Testing

Click here to see SQL Profiler details for Red Filter's Query

Click here to see SQL Profiler details for my Query

<强> For More Information You can see SQL Fiddle