【发布时间】:2021-09-20 17:49:54
【问题描述】:
我有一个数据表,其中显示单个数据的多行。在下面的示例中,我有一个名为“Location Type”的列,其中显示“BH”和“TPI”。 BH 和 TPI 各有一个特定的位置,显示在“位置”列中。我想要两个新列来显示该行的位置数据,而不是为 BH 和 TPI 设置一个新行。我在下面包含了几行数据。我怀疑我需要在这里使用 PIVOT,但我一直很难弄清楚 PIVOT 需要进入的位置。有人可以提供一些指导或向我展示解决方案吗?
这是来自查询的数据示例。
| API14 | First Prod Date | Location Type | Location |
|---|---|---|---|
| 43013540070000 | 2/8/2021 | BH | Township 3S Range 4W Section 17 DUCHESNE County |
| 43013540070000 | 2/8/2021 | TPI | Township 3S Range 4W Section 18 DUCHESNE County |
这是我希望看到的格式:
| API14 | First Prod Date | BH Location | TPI Location |
|---|---|---|---|
| 43013540070000 | 2/8/2021 | Township 3S Range 4W Section 17 DUCHESNE County | Township 3S Range 4W Section 18 DUCHESNE County |
到目前为止,这是我的代码:
DECLARE @SearchYear AS VARCHAR(4) = '2021'
DECLARE @SearchMonth AS VARCHAR(2) = '6'
SELECT
dbo.BuildAPI14(Well.WellID, Construct.SideTrack, Construct.Completion) AS 'API14',
CAST(ConstructDate.EventDate AS DATE) AS 'First Prod Date',
Loc.LocType AS 'Location Type',
CONCAT('Township ',LocExt.Township,LocExt.TownshipDir,' ','Range ',LocExt.Range,LocExt.RangeDir,' Section ',LocExt.Sec,' ',RefCounty.CountyName,' County') AS 'Location',
tblAPDTracker.SpacingRule AS 'Spacing Rule',
Lease.Number AS 'Entity Number',
WellHistory.WHComments AS 'Well History Comments'
FROM Well
LEFT JOIN Construct ON Construct.WellKey = Well.PKey
LEFT JOIN ConstructReservoir ON ConstructReservoir.ConstructKey = Construct.PKey
LEFT JOIN Lease ON Lease.Pkey = ConstructReservoir.LeaseKey
LEFT JOIN WellHistory ON WellHistory.WellKey = Construct.WellKey
LEFT JOIN tblAPDTracker ON LEFT(tblAPDTracker.APINO,10) = Well.WellID
LEFT JOIN Loc ON loc.ConstructKey = Construct.PKey AND Loc.LocType IN ('BH','TPI')
LEFT JOIN LocExt ON LocExt.LocKey = Loc.PKey
LEFT JOIN ConstructDate ON ConstructDate.ConstructKey = Construct.PKey AND ConstructDate.Event = 'FirstProduction'
LEFT JOIN RefCounty ON RefCounty.PKey = LocExt.County
WHERE
WorkType = 'ENTITY' AND
WellHistory.ModifyUser = 'UTAH\rachelmedina' AND
YEAR(WellHistory.ModifyDate) = @SearchYear AND
MONTH(WellHistory.ModifyDate) = @SearchMonth
GROUP BY
Well.WellID,
Construct.SideTrack,
Construct.Completion,
ConstructDate.EventDate,
Loc.LocType,
LocExt.Township,
LocExt.TownshipDir,
LocExt.Range,
LocExt.RangeDir,
LocExt.Sec,
RefCounty.CountyName,
tblAPDTracker.SpacingRule,
Lease.Number,
WellHistory.WHComments,
WellHistory.ModifyDate
ORDER BY
Well.WellId,
WellHistory.ModifyDate DESC
【问题讨论】:
-
助您一臂之力_minimal reproducible example
-
@jarlh 我正在尝试将示例中的数据添加到表格中,以便任何人都可以获取它。它在我的编辑中看起来不错,但是一旦我点击保存它就会变成乱码。我会继续努力,看看我是否可以进一步简化。
-
这里的大多数人都希望样本表数据_和预期结果为格式化文本,而不是图像。 (而且我什至无法阅读那个微小的图像文本......)
-
@jarlh 我将添加一些示例数据以及我希望看到的结果。
-
@jarlh 我可以对这篇文章做些什么来获得更多回复吗?我添加了一些示例数据和预期的结果。我还缩短了查询以针对示例数据。
标签: sql pivot pivot-table