I have a table as follows:
| OrganizationCode | PrerequisitesName | PrerequisitesValue | Remarks |
| ------------ | ------------ | ------------ | ------------ |
| AFA | ppco | 1 | NULL |
| AFA | liability | 1 | NULL |
I will need a result table like this:
OrganizationCode | IsPpco | PpcoRemarks | IsLiability | LiabilityRemarks |
---|---|---|---|---|
AFA | true | NULL | true | NULL |
What operator can I use in SQL Server to achieve this result ?
2条答案
按热度按时间r7s23pms1#
Be careful with PIVOT, it will group by everything on the table even if you don't select some columns. If necessary use a CTE before PIVOTING. For example, here it will group everything including PrerequisitesValue
u3r8eeie2#
There are generally two ways you can do this: You can use the actual
PIVOT
operator, or use something likeMAX
instead (this is generally called a "crosstab pivot"; i think, someone correct me if I'm wrong, I may be using the wrong terminology here). I find the latter approach generally easier to reason about as the pivot syntax is not very straight forward. This is even more important in this case as you want to pivot values from two columns.The idea is you check if the
Prereq
name is what you want, and if it is, you project it's value. Otherwise, you projectnull
. TheMAX
operator will pick the value you want for the rows that match theIIF
constraint, and the nulls will fall out of the query: