将数据从一个表复制到另一个表并设置固定值?

时间:2011-01-31 13:05:56

标签: sql rdbms

我正在使用以下SQL语句将数据从TableA复制到TableB。

INSERT INTO TableB (url, pageViews)
SELECT DISTINCT TOP(5) url AS url, SUM(HitCount) As pageViews
FROM TableA
WHERE (url LIKE '%www%site') AND (YEAR(dtDate) = 2011) AND (MONTH(dtDate) = 1)
GROUP BY url
ORDER BY pageViews DESC

目前,这可以很好地将url和pageViews数据放入TableB,如下所示(请忽略点 - 这是为了将所有内容格式化为一个表格!)。


|URL            | pageViews     | ranking

|www.site.com   | 25220         | NULL

|www.site.com/a | 25230         | NULL

|www.site.com/b | 25433         | NULL

但排名列为NULL。对于我从TableA带来的每一行,我想将排名列的值(仅存在于表B中)设置为“Top5”,如下所示:


|URL            | pageViews     | ranking

|www.site.com   | 25220         | Top5

|www.site.com/a | 25230         | Top5

|www.site.com/b | 25433         | Top5

我非常感谢你提供任何帮助。

非常感谢:)

2 个答案:

答案 0 :(得分:4)

简单地为每行选择常量值:

INSERT INTO TableB (url, pageViews, ranking)
SELECT DISTINCT TOP(5) url AS url, SUM(HitCount) As pageViews, 'Top5' AS ranking

答案 1 :(得分:1)

  

但排名列为NULL。对于   我带来的每一行   TableA,我想设置值   排名列(仅存在   在表B

您没有从TableB中选择ranking列:

INSERT INTO TableB (url, pageViews, ranking)
SELECT DISTINCT TOP(5) url AS url, SUM(HitCount) As pageViews, ranking
FROM TableA
WHERE (url LIKE '%www%site') AND (YEAR(dtDate) = 2011) AND (MONTH(dtDate) = 1)
GROUP BY url
ORDER BY pageViews DESC