0

我正在尝试从单个表中选择特定的数据集,然后将它们分组显示在单个字段下。然而,这会为每个 case 语句创建一行。

理想情况下,我希望每个报价单都有一行,每个字段都针对它。

有没有人知道我如何改进我到目前为止所做的事情?

select
   KeyField as Quote,
   CASE WHEN FieldName = 'QTY001' THEN AlphaValue ELSE null END as [QTY],
   CASE WHEN FieldName = 'CON002' THEN AlphaValue ELSE null END as [Conductors],
   CASE WHEN FieldName = 'COP001' THEN AlphaValue ELSE null END as [Copper Size],
   CASE WHEN FieldName = 'COR001' THEN AlphaValue ELSE null END as [Core Length],
   CASE WHEN FieldName = 'COR002' THEN AlphaValue ELSE null END as [Core Inside],
   CASE WHEN FieldName = 'END001' THEN AlphaValue ELSE null END as [End Winding],
   CASE WHEN FieldName = 'KV_001' THEN AlphaValue ELSE null END as [KV],
   CASE WHEN FieldName = 'KW_001' THEN AlphaValue ELSE null END as [KW],
   CASE WHEN FieldName = 'NAM001' THEN AlphaValue ELSE null END as [OEM],
   CASE WHEN FieldName = 'SLO001' THEN AlphaValue ELSE null END as [Slots],
   CASE WHEN FieldName = 'SPE001' THEN AlphaValue ELSE null END as [Speed],
   CASE WHEN FieldName = 'TUR001' THEN AlphaValue ELSE null END as [Turns],
   CASE WHEN FieldName = 'TYP001' THEN AlphaValue ELSE null END as [Type/Description]
from 
   AdmFormData 
where 
   FormType = 'QOT'
4

3 回答 3

1

添加GROUP BY子句

SELECT ...,
      MAX(CASE WHEN FieldName = 'QTY001' THEN AlphaValue ELSE null END) as [QTY],
       .....
FROM...
WHERE...
GROUP BY KeyField
于 2013-05-16T09:11:20.080 回答
1

作为多个case when ...语句的替代方案,您可以使用 SQLServer 的 PIVOT 工具:

select
   KeyField as Quote,
   [QTY001] as [QTY],
   [CON002] as [Conductors],
   [COP001] as [Copper Size],
   [COR001] as [Core Length],
   [COR002] as [Core Inside],
   [END001] as [End Winding],
   [KV_001] as [KV],
   [KW_001] as [KW],
   [NAM001] as [OEM],
   [SLO001] as [Slots],
   [SPE001] as [Speed],
   [TUR001] as [Turns],
   [TYP001] as [Type/Description]
from 
   (select KeyField, FieldName, AlphaValue 
    from AdmFormData
    where FormType ='QOT') as s
pivot
   (max(AlphaValue) for FieldName in 
    ([QTY001], [CON002], [COP001], [COR001], [COR002], [END001], [KV_001], [KW_001], [NAM001], [SLO001], [SPE001], [TUR001], [TYP001])
   ) as p
于 2013-05-16T09:53:59.853 回答
0

如果您有 MSSQL 2005 及更高版本,则可以使用PIVOT命令:

SELECT KeyField, [QTY001], [CON002], [COR001]
FROM (
    SELECT KeyField, FieldName, AlphaValue FROM data
  ) AS SourceTable
PIVOT (
    MAX(AlphaValue)
    FOR FieldName IN([QTY001], [CON002], [COR001])
  ) AS PivotTable

在其他情况下,您的解决方案是实现这一目标的唯一方法。

SQLFiddle

于 2013-05-16T09:55:15.150 回答