我想比较两列i的历史数据,我希望将今年的数据与上一年的数据进行比较。我在同一张桌子上进行了内部联接
select
a.dt,a.brand,
a.total_fans,
a.fan_growth,
b.total_fans as total_fans_BOY,
b.fan_growth as Fan_Growth_BOY,
b.Before_One_Year INTO TM_DATA_BOY
from
TEMP_TM_DATA a
LEFT JOIN TEMP_TM_DATA b
on a.dt = b.Before_One_Year
and a.brand = b.brand
and a.source = b.source
(男孩=一年前)
数据在表TEMP_TM_DATA中,我使用Before_One_Year
在TEMP_TM_DATA
中创建了一个名为DATEADD(Year,-1,dt)
的列,然后在上面的查询中使用。
The table structure is like this
+----------------+------------+----------------+---------------------+
| Present Date |No of fans | NO Of fans BOY |Before One year(date)|
+----------------+------------+----------------+---------------------+
| 28-Jan-2014 | 30 | 24 |28-Jan-2013 |
| 1-Feb-2014 | 35 | 30 |1-Feb-2013 |
+-------+--------+------------+----------------+---------------------+
结果集不像上面那样显示,而是像这样显示
+----------------+------------+----------------+---------------------+
| Present Date |No of fans | NO Of fans BOY |Before One year(date)|
+----------------+------------+----------------+---------------------+
| 28-Jan-2014 | 30 | 24 |*28-Jan-2014* |
| 1-Feb-2014 | 35 | 30 |*1-Feb-2014* |
+-------+--------+------------+----------------+---------------------+
答案 0 :(得分:0)
试试这个:
SELECT a.dt,
a.brand,
a.total_fans,
a.fan_growth,
b.total_fans AS Total_Fans_BOY,
b.fan_growth as Fan_Growth_BOY,
CONVERT(VARCHAR, DATEADD(YEAR, -1, a.dt), 106) AS Before_One_Year
INTO TM_DATA_BOY
FROM TEMP_TM_DATA AS a LEFT JOIN
TEMP_TM_DATA AS b
ON a.brand = b.brand AND
a.source = b.source AND
CONVERT(VARCHAR, a.dt, 101), CONVERT(VARCHAR, DATEADD(YEAR, -1, a.dt), 101)
答案 1 :(得分:0)
我使用了这个查询
select a.dt, a.brand, a.total_fans, a.fan_growth, b.total_fans as total_fans_BOY, b.fan_growth as Fan_Growth_BOY, a.Before_One_Year INTO TM_DATA_BOY from TEMP_TM_DATA a LEFT JOIN TEMP_TM_DATA b on a.Before_One_Year=b.dt and a.brand=b.brand and a.source=b.source
这解决了一切