1

彼/彼女がその日に出席したかどうかを示すIDに対する出席記録があり、そのIDに対して複数の行にある単一の行でSQLクエリを介してデータを表示したい. SOこの問題をできるだけ早く理解するのを手伝ってください。

クエリを実行した後、データベースからこの結果を取得します。

abc   1/2/2013      Present

abc   2/2/2013      Present

abc   3/2/2013      Present

abc   4/2/2013      Present

abc   5/2/2013      Present

abc   6/2/2013      Present

Expected Result:

Name   Date1     Date2     Date3      Date4       Date5

abc    Present   Present   Present    Present     Present
4

1 に答える 1

1

を使用してはならない場合は、行番号とグループ化 ( DEMO )PIVOTを使用して同じ効果を得ることができます。

select
  name
  ,max(case when rn=1 then description end) as date1
  ,max(case when rn=2 then description end) as date2
  ,max(case when rn=3 then description end) as date3
  ,max(case when rn=4 then description end) as date4
  ,max(case when rn=5 then description end) as date5
from (
  select name, date, description,
    row_number() over (partition by name order by date) rn from Table1
) T
group by name

これは、クエリにハードコードした数の日付のみを処理することに注意してください。動的にする必要がある場合 (つまり、事前に必要な日付列の数がわからない場合)、グループごとの最大日付カウントに基づいて上記の SQL コードを動的に生成する必要がある場合があります。

于 2013-04-16T17:36:57.680 に答える