我有一张桌子DataDefinitions
。我写了一个查询,以下列格式从这个表中获取数据:
但我想将Name
列中的公用名部分与枢轴结果数据分开,以获得以下格式的记录:
请帮助我在SQL Server存储过程中如何执行此操作。
我获得第一张表的查询是
SELECT
d.Name
, r.latestValueDec AS value
FROM IDReadingLatestValues r
JOIN DataDefinitions d ON r.dataDefinitionId = d.dataDefinitionId
答案 0 :(得分:1)
丑陋,但工作......
SELECT
Name = SUBSTRING(d.Name, 1, PATINDEX('%Phase%', d.Name)
, [Phase A] = SUM(CASE WHEN d.Name LIKE '%Phase A' THEN r.latestValueDec END)
, [Phase B] = SUM(CASE WHEN d.Name LIKE '%Phase B' THEN r.latestValueDec END)
, [Phase C] = SUM(CASE WHEN d.Name LIKE '%Phase C' THEN r.latestValueDec END)
FROM dbo.IDReadingLatestValues r
JOIN dbo.DataDefinitions d ON r.dataDefinitionId = d.dataDefinitionId
GROUP BY SUBSTRING(d.Name, 1, PATINDEX('%Phase%', d.Name)
PS。请规范化您的数据......
答案 1 :(得分:1)
如果它总是最多三个阶段,你可以像这样使用条件聚合:
SELECT replace(replace(replace(t.name,'Phase A',''),'Phase B',''),'Phace C','') as name,
max(CASE WHEN s.latestValueDesc like '%Phase A' then s.latestValueDesc end) as Phase_A,
max(CASE WHEN s.latestValueDesc like '%Phase B' then s.latestValueDesc end) as Phase_B,
max(CASE WHEN s.latestValueDesc like '%Phase C' then s.latestValueDesc end) as Phase_C
FROM IDReadingLatestValues s
JOIN DataDefinitions t
ON s.dataDefinitionId = t.dataDefinitionId
GROUP BY replace(replace(replace(t.name,'Phase A',''),'Phase B',''),'Phace C','')
我确信有一种更漂亮的方法可以做到这一点,但它应该按照您的预期运作。