GROUP BY第二部分的均质容器

时间:2013-06-18 00:30:02

标签: sql sql-server group-by

我有三张桌子,其中一张我需要更新:

CREATE TABLE Containers (
  ID int PRIMARY KEY,
  FruitType int
)
CREATE TABLE Contents (
  ContainerID int,
  ContainedFruit int
)
CREATE TABLE Fruit (
  FruitID int,
  Name VARCHAR(16)
)

INSERT INTO Fruit VALUES ( 0, 'Mixed' )
INSERT INTO Fruit VALUES ( 1, 'Apple' )
INSERT INTO Fruit VALUES ( 2, 'Banana' )
INSERT INTO Fruit VALUES ( 3, 'Cherry' )
INSERT INTO Fruit VALUES ( 4, 'Date' )

INSERT INTO Containers VALUES ( 101, 0 )
INSERT INTO Containers VALUES ( 102, 0 )
INSERT INTO Containers VALUES ( 103, 0 )
INSERT INTO Containers VALUES ( 104, 3 )

INSERT INTO Contents VALUES ( 101, 1 )
INSERT INTO Contents VALUES ( 101, 1 )
INSERT INTO Contents VALUES ( 102, 1 )
INSERT INTO Contents VALUES ( 102, 2 )
INSERT INTO Contents VALUES ( 102, 3 )
INSERT INTO Contents VALUES ( 103, 3 )
INSERT INTO Contents VALUES ( 103, 4 )
INSERT INTO Contents VALUES ( 104, 3 )

我们假设这是我的数据库的状态。请注意Fruit表使用了两次。一旦描述容器的内容,并且一次描述容器是否仅包含一种类型的水果或是否可以混合。设计不好的IMO,但为时已晚,无法改变它。

问题是当容器101真的应该是APPLE时,它被错误地标记为MIXED。具有多种相同类型内容的容器仍然是同质容器,应该标记为这样。

我知道如何查找查找错误标记为混合的容器的查询:

SELECT Contents.ContainerID
FROM Contents
INNER JOIN Containers ON
  Contents.ContainerID = Containers.ID AND
  Containers.FruitType = 0
GROUP BY Contents.ContainerID
HAVING COUNT( DISTINCT Contents.ContainedFruit ) = 1

但是,我不知道如何更新已发生此错误的Container中的每一行。那是我的问题。

1 个答案:

答案 0 :(得分:0)

这样做:

UPDATE Container
SET Container.FruitType = Proper.ProperType
FROM Container
INNER JOIN
(
  SELECT Contents.ContainerID, 
  MAX(Contents.ContainedFruit) ProperType
FROM Contents
INNER JOIN Container ON
  Contents.ContainerID = Container.ID AND
  Container.FruitType = 0
GROUP BY Contents.ContainerID
HAVING COUNT( DISTINCT Contents.ContainedFruit ) = 1
) Proper
ON Container.ID = Proper.ContainerID

SQL Fiddle