使用子查询更新表

时间:2014-01-08 12:12:02

标签: sql sql-server subquery

我在数据库中使用下表(Access - Microsoft SQL Server):

| Product Id |  Month    | Sales |
----------------------------------
| 1144       |  1        | 100   |
| 20131120   |  1        | 200   |
| 1144       |  2        | 333   |
| 1144       |  3        | 333   |
| 1144       |  4        | 333   |
| 1144       |  5        | 333   |
| 20131120   |  2        | 200   |

我想在表中添加一个新列,它将显示每个产品在特定月份销售的数月。我需要将此信息保存在数据库中,在此表中。

更新表后我想得到表:

| Product Id |  Month    | Sales | Counter |
-------------------------------------------|
| 1144       |  1        | 100   |   0     |
| 20131120   |  1        | 200   |   0     |
| 1144       |  2        | 333   |   1     |
| 1144       |  3        | 333   |   2     |
| 1144       |  4        | 333   |   3     |
| 1144       |  5        | 333   |   4     |
| 20131120   |  2        | 200   |   1     |

例如,对于product = 1144和month = 3,counter = 2,因为此项目已经出现两次,直到3个月。

我想用一个查询更新列计数器(update set =(select ...))。你能帮我构建一下这个查询吗?

3 个答案:

答案 0 :(得分:2)

SqlServer中,您可以使用row_number()

直接投影列排名
select 
    productid, 
    [month], 
    sales, 
    row_number() over (partition by productid order by [month]) - 1 as [Rank]
from mysales

假设列[ProductId, MonthId]构成一个键,您可以坚持:

-- Create new column
ALTER TABLE mysales ADD [Rank] INT
GO

-- Set the new Column
UPDATE m 
    SET m.[Rank] = X.[Rank]
    FROM mysales m
    INNER JOIN
       (
         SELECT 
            ProductId, 
            Month, 
            row_number() over (partition by productid order by [month]) - 1 AS [Rank]
         FROM MySales
        ) X
    ON m.ProductId = X.ProductID AND m.[Month] = X.[Month];

Fiddle here

答案 1 :(得分:0)

如果我理解正确的话,这几个月总是顺序的,对吗?然后只需将Counter列更新为(Month - 1)。

UPDATE [table] SET [Counter] = [Month] - 1

答案 2 :(得分:0)

此查询应检索正确的数据:

SELECT    m1.product_id, m1.month, m1.sales, COUNT(m2.month) - 1 AS counter
  FROM    mysales AS m1 INNER JOIN
          mysales AS m2 ON m1.product_id = m2.product_id AND m1.month >= m2.month
 GROUP BY m1.product_id, m1.month, m1.sales

所以在添加计数器列后更新表的语句是:

UPDATE    mysales
   SET    counter = x.counter
  FROM    (SELECT    m1.product_id, m1.month, COUNT(m2.month) - 1 AS counter
             FROM    mysales AS m1 INNER JOIN
                     mysales AS m2 ON m1.product_id = m2.product_id AND m1.month >= m2.month
            GROUP BY m1.product_id, m1.month) AS x INNER JOIN
          mysales ON x.product_id = mysales.product_id AND x.month = mysales.month

update语句的这种语法适用于SqlServer,我不知道它是否也适用于MS Access。