我有一个表 - 它就像几个表连接在一起,因为[Col1]接受两个不同的字符串,[Value]接受与[Col1]字符串相关的数值。分段有2组列。分析每个细分和稍后的细分组合。日期戳也可用。
Col1 datestamp Value
ret 1/10/14
ent 1/10/14
ret 2/1/14
ent 2/1/14
完成的表格如下所示:
Col1ret Col2ent datestamp Value-ret Value-ent
ret ent 1/10/14
ret ent 2/1/14
执行此操作的SQL脚本是什么?
答案 0 :(得分:1)
您可以使用PIVOT TABLE转换您的查询结果
CREATE TABLE #tmp (col1 nvarchar(5),datestamp DATETIME ,value int)
INSERT INTO #tmp VALUES ('ret',CAST('2014-10-01' AS DATE),null)
INSERT INTO #tmp VALUES ('ent',CAST('2014-10-01' AS DATE),null)
INSERT INTO #tmp VALUES ('ret',CAST('2014-2-1' AS DATE),null)
INSERT INTO #tmp VALUES ('ent',CAST('2014-2-1' AS DATE),null)
SELECT pv.ret
,pv.ent
,pv.datestamp
,pv.value
FROM (
SELECT t.col1
,t.datestamp
,t.value
FROM #tmp t
) as a
PIVOT (
MAX(col1)
FOR [col1] IN ([ret],[ent])
) as pv
DROP TABLE #tmp
你会得到像这样的查询结果
ret ent datestamp value
-------------------------------------
ret ent 2014-02-01 00:00:00.000 NULL
ret ent 2014-10-01 00:00:00.000 NULL
更多信息请参阅以下链接 https://technet.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx
答案 1 :(得分:1)
只需做一个简单的JOIN
:
select t1.Col1 as Col1ret, t2.Col1 as Col2ent, t1.datestamp, t1.value as value-ret, t2.value as value-ent
from tablename t1
join tablename t2 on t1.datestamp = t2.datestamp
where t1.Col1 = 'ret'
and t2.Col1 = 'ent'
因为它的MySQL也许你需要替换"背叛?