次の行を含むテーブルがあります。
次の結果を表示するビューを作成したい(元のテーブルを変更せずに):
ID、日、月、年が同じ行ごとに、コストとカウントを1行残し、他の行に0を挿入します。
次の行を含むテーブルがあります。
次の結果を表示するビューを作成したい(元のテーブルを変更せずに):
ID、日、月、年が同じ行ごとに、コストとカウントを1行残し、他の行に0を挿入します。
あなたはこのようなことをすることができます:
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
最初の行を選び出し、異なる動作をさせるためのステートメントを使用します。
これは、を必要としないポータブルなアプローチ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
または、一般的なテーブル式を使用します。
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
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