我有一个产品允许在GUI中创建自定义字段。我创建了三个字段:系统发货日期,系统保修结束日期和系统保修说明。遗憾的是,系统将这些填充为行,而不是列。
示例:
Machine_GroupID | agentGuid | fieldName | fieldValue
-----------------------------------------------------------------------------
systemABC.companyABC | 57537921 | System Ship Date | 1/1/1900
systemABC.companyABC | 57537921 | System Warranty End Date | 1/1/1950
systemABC.companyABC | 57537921 | System Warranty Notes | Test notes
system123.companyABC | 48394844 | System Ship Date | 1/1/1900
system123.companyABC | 48394844 | System Warranty End Date | 1/1/1950
system123.companyABC | 48394844 | System Warranty Notes | Test notes
systemXYZ.companyABC | 99948403 | System Ship Date | 1/1/1900
systemXYZ.companyABC | 99948403 | System Warranty End Date | 1/1/1950
systemXYZ.companyABC | 99948403 | System Warranty Notes | Test notes
我需要将系统发货日期作为列,系统保修结束日期作为列,将系统保修说明作为列返回。如果我使用CASE WHEN语句:
CASE WHEN sim.fieldName = 'System Ship Date'
THEN sim.fieldValue END AS 'System Ship Date',
CASE WHEN sim.fieldName = 'System Warranty End Date'
THEN sim.fieldValue END AS 'System Warranty End Date',
CASE WHEN sim.fieldName = 'System Warranty Notes'
THEN sim.fieldValue END AS 'System Warranty Notes'
因此,数据显示在每台计算机上:
header1 header2 header3
data1 NULL NULL
NULL data2 NULL
NULL NULL data3
我需要它看起来像这样:
header1 header2 header3
data1 data2 data3
我以为我可以以某种方式使用MAX(),但我是新手而且它超出了我。或者我知道我可以创建一个临时表,但我也不知道。我已经在网上和堆栈上进行了广泛的搜索,但是我能得到的就是CASE WHEN语句。
答案 0 :(得分:7)
为什么不加入SELF?保持简单......
SELECT
s1.Machine_GroupID, s1.agentGuid,
s1.fieldValue, s2.fieldValue, s3.fieldValue
FROM
sim s1
JOIN sim s2 ON s1.Machine_GroupID = s2.Machine_GroupID
JOIN sim s3 ON s1.Machine_GroupID = s3. Machine_GroupID
WHERE
s1.fieldName = 'System Ship Date' AND
s2.fieldName = 'System Warranty End Date' AND
s2.fieldName = 'System Warranty Notes'
答案 1 :(得分:6)
在MS SQL中:
SELECT
Machine_GroupID, agentGuid, "System Ship Date", "System Warranty End Date", "System Warranty Notes"
FROM
(
SELECT
Machine_GroupID, agentGuid, fieldName, MAX(fieldValue) AS Value
FROM
sim
GROUP BY
Machine_GroupID, agentGuid, fieldName
) AS X
PIVOT
(MAX(Value) FOR fieldName IN ("System Ship Date", "System Warranty End Date", "System Warranty Notes")) AS Y
GROUP BY
子句在您的情况下并不是绝对必要的,但没有它PIVOT
有时会返回无关的行,而不像您的第一个表。