私はテーブル 'AnimalInformation'を持っており、以下のような購入日に基づいてカラムをピボットしたいと考えています。私はピボットで試しましたが、私が必要とするものを正確に得られませんでした。あなたは何か助けてくれますか?2つのカラムに基づいてピボットするSQLロジック
Result should look like
PurchaseDate | CatInfo| DogInfo | FishInfo | CatDate | DogDate | FishDate
----------------------------------------------------------------------------------
1/1/2016 | Good | Fair | NotGood | 10/10/2016 | 11/10/2016 | 12/10/2016
2/2/2016 | Bad | Good | Good | 9/9/2016 | 10/9/2016 | 11/9/2016
##Table##
CREATE TABLE [dbo].[AnimalInformation](
[UniqueId] [int] IDENTITY(1,1) NOT NULL,
[PurchaseDate] [datetime] NOT NULL,
[Animal] [nvarchar](50) NOT NULL,
[HealthDate] [datetime] NOT NULL,
[AnimalCondition] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_AnimalInformation] PRIMARY KEY CLUSTERED
(
[UniqueId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
## Insert Statement ##
Insert into AnimalInformation values ('1/1/2016' ,'Cat','10/10/2016','Good')
Insert into AnimalInformation values ('1/1/2016' ,'Dog','11/10/2016','Fair')
Insert into AnimalInformation values ('1/1/2016' ,'Fish','12/10/2016','Not Good')
Insert into AnimalInformation values ('2/2/2016' ,'Cat','9/9/2016','Bad')
Insert into AnimalInformation values ('2/2/2016' ,'Dog','10/9/2016','Good')
Insert into AnimalInformation values ('2/2/2016' ,'Fish','11/9/2016','Good')
## My Query ##
SELECT * FROM
(
SELECT
PurchaseDate,
Animal,
AnimalCondition,
HealthDate,
(Animal + 'Info') AnimalHealthInfo,
(Animal + 'Date') AnimalHealthDate
FROM
AnimalInformation
) X
PIVOT (MAX(AnimalCondition) FOR AnimalHealthInfo IN ([CatInfo],[DogInfo],[FishInfo])
) As P1
PIVOT (MAX(HealthDate) FOR AnimalHealthDate IN ([CatDate],[DogDate],[FishDate])
) AS P2
ありがとうございました!条件付き集約がこの状況に最適であると私は感じます。再度、感謝します !! – user3600663