想要以表格的形式获取数据

时间:2011-08-23 11:49:52

标签: sql sql-server tsql sql-server-2008 pivot

我写了这个查询:

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

输出是:

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

我想以这种方式得到结果:

  Name           Description       Status
  TestField      abcdef            testing123       

请建议如何通过在sql中编写查询来获得此结果。

3 个答案:

答案 0 :(得分:4)

您想要的是 pivoting ,从SQL Server 2005开始,您可以在PIVOT子句的帮助下,使用标准语法在Transact-SQL中进行透视。< / p>

您的查询可以转换为与PIVOT一起使用,如下所示:

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

答案 1 :(得分:2)

SELECT
   FieldValue, 
   [Name], 
   [Description], 
   [Status]
FROM
   myTable -- OR (your posted query) myQuery
PIVOT
(
   MIN(FieldValue)
   FOR FieldName IN ([Name], [Description], [Status])
) AS myPivot;

答案 2 :(得分:0)

Tahnk你这么多Andriy M .... 只有很少的变化,我可以得到理想的结果。 Chenges如下

 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