0

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

在此处输入图像描述

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

在此处输入图像描述

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

4

4 回答 4

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语句来挑出第一个并使其行为不同。

在这里查看它在 SQL Fiddle 上的工作。

于 2012-05-23T14:30:24.257 回答
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
于 2012-05-23T14:31:08.117 回答
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
于 2012-05-23T14:35:26.980 回答
-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

单击此处查看 Red Filter 查询的 SQL Profiler 详细信息

单击此处查看我的查询的 SQL Profiler 详细信息

有关更多信息,您可以查看 SQL Fiddle

于 2012-05-23T16:58:32.193 回答