1

I have written this query:

SELECT
    d.DetailId, 
    i.ItemId,
    d.fieldId,
    d.Fieldvalue,
    f.Name 
FROM
   EntityItemDetails d 
   inner join EntityItems i 
      on i.ItemId = d.ItemId 
   inner join Fields f 
      on f.Id = d.FieldId
WHERE
   i.EntityId = 1

Output is:

DetailId ItemId  FieldId   FieldValue     FieldName
1       1        9         Defect1        Name
2       1        10        abcdef         Description
5       1        11        testing123     Status

I want result in this way:

  Name           Description       Status
  TestField      abcdef            testing123       

Please suggest how to get this result by writing a query in sql.

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
Archana
  • 11
  • 1

3 Answers3

4

What you want is called pivoting, and starting from SQL Server 2005, you can use a standard syntax for pivoting in Transact-SQL, with the help of the PIVOT clause.

Your query could be transformed for use with PIVOT like this:

WITH source AS (
  /* this CTE is actually your original query */
  SELECT
    EntityItemDetails.DetailId,
    EntityItems.ItemId,
    EntityItemDetails.fieldId,
    EntityItemDetails.Fieldvalue,
    Fields.Name
  FROM EntityItemDetails
    INNER JOIN EntityItems ON EntityItems.ItemId = EntityItemDetails.ItemId
    INNER JOIN Fields ON Fields.Id = EntityItemDetails.FieldId
  WHERE EntityItems.EntityId = 1
)

SELECT
  ItemId,
  Name,
  Description,
  Status
FROM (
  SELECT ItemId, FieldName, FieldValue
  FROM source
) s
PIVOT (
  MAX(FieldValue) FOR FieldName IN (
    Name,
    Description,
    Status
    /* add other possible names as necessary */
  )
) p
Andriy M
  • 76,112
  • 17
  • 94
  • 154
2
SELECT
   FieldValue, 
   [Name], 
   [Description], 
   [Status]
FROM
   myTable -- OR (your posted query) myQuery
PIVOT
(
   MIN(FieldValue)
   FOR FieldName IN ([Name], [Description], [Status])
) AS myPivot;
Chains
  • 12,541
  • 8
  • 45
  • 62
0

Tahnk u so much Andriy M.... with very few changes I could get the desired result. Chenges are as below

 WITH source AS ( 
  /* this CTE is actually your original query */  
    SELECT     EntityItemDetails.CreatedDate,     EntityItems.EntityItemId,
      EntityItemDetails.fieldId, 
         EntityItemDetails.Fieldvalue, 
              Fields.Name FieldName  FROM EntityItemDetails 
                INNER JOIN EntityItems ON EntityItems.EntityItemId =         EntityItemDetails.EntityItemId
                     INNER JOIN Fields ON Fields.Id = EntityItemDetails.FieldId     WHERE EntityItems.EntityId = 1 and (FieldId=9 or FieldId=10 or FieldId=11) ) 
                      SELECT   EntityItemId,   [Name],   [Description],   [Status] 
                      FROM (   SELECT EntityItemId, FieldName, FieldValue   FROM   source ) s 
                      PIVOT (   MAX(FieldValue) FOR FieldName IN (     [Name],       [Description],     [Status]  ) ) p
Archana
  • 11
  • 1