SQL Server T-SQL rotating table

r7knjye2  于 2023-11-16  发布在  其他
关注(0)|答案(2)|浏览(123)

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:

OrganizationCodeIsPpcoPpcoRemarksIsLiabilityLiabilityRemarks
AFAtrueNULLtrueNULL

What operator can I use in SQL Server to achieve this result ?

r7s23pms

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

  1. DECLARE @t TABLE
  2. (
  3. OrganizationCode VARCHAR(3),
  4. PrerequisitesName VARCHAR(20),
  5. PrerequisitesValue INT,
  6. Remarks VARCHAR(20)
  7. );
  8. INSERT INTO @t VALUES('AFA', 'ppco',1, null);
  9. INSERT INTO @t VALUES('AFA', 'liability',1, null);
  10. INSERT INTO @t VALUES('XYZ', 'ppco',1, 'ppcoRemark');
  11. INSERT INTO @t VALUES('ABC', 'liability',1, 'liabilityRemark');
  12. SELECT
  13. pvt.OrganizationCode,
  14. CASE WHEN pvt.ppco > 0 THEN 'True' ELSE 'False' end IsPpco,
  15. CASE WHEN pvt.ppco > 0 THEN pvt.Remarks END AS PpcoRemarks,
  16. CASE WHEN pvt.[liability] > 0 THEN 'True' ELSE 'False' END IsLiability,
  17. CASE WHEN pvt.[liability] > 0 THEN pvt.Remarks END AS LiabilityRemarks
  18. FROM
  19. @t t PIVOT (COUNT(PrerequisitesName) FOR PrerequisitesName IN ([liability],[ppco])) AS pvt;
展开查看全部
u3r8eeie

u3r8eeie2#

There are generally two ways you can do this: You can use the actual PIVOT operator, or use something like MAX 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 project null . The MAX operator will pick the value you want for the rows that match the IIF constraint, and the nulls will fall out of the query:

  1. ;with a (OrgCode, PrereqName, PrereqValue, Remarks) as
  2. (
  3. select 'AFA', 'ppco', 1, cast(null as varchar(100)) union all
  4. select 'AFA', 'liability', 1, null
  5. ), b as
  6. (
  7. select
  8. OrgCode,
  9. IsPpco = max(iif(PrereqName = 'ppco', PrereqValue, null)),
  10. IsLiability = max(iif(PrereqName = 'liability', PrereqValue, null)),
  11. LiabilityRemarks = max(iif(PrereqName = 'liability', Remarks, null))
  12. from a
  13. group by OrgCode
  14. )
  15. select
  16. OrgCode,
  17. IsPpco = iif(IsPpco = 1, 'True', 'False'),
  18. IsLiability = iif(IsLiability = 1, 'True', 'False'),
  19. LiabilityRemarks
  20. from b
展开查看全部

相关问题