使用子查询插入表中

时间:2014-11-06 20:37:40

标签: sql-server tsql select insert-into

我正在处理一项我从未做过的查询,而且我仍然坚持如何继续。我想成为一个插入命令。

我试图做的伪代码是这样的:

For each player 
    insert into CurrentHand table by getting x number of cards needed 
       so all the players have 10 cards in their hands.

因此,如果玩家1手中有3张牌,他将获得7张新牌。如果他手中有5张牌,Play 2将获得5张新牌。

到目前为止,我已经接受了这个选择声明,但感觉我使用了错误的方法。

DECLARE @MaxHandCount int
SET @MaxHandCount = 10

SELECT Player.PlayerId
    , (SELECT COUNT(1) FROM CurrentHand WHERE PlayerId = Player.PlayerId AND IsUsed = 0) AS CurrentHandCount
    , (@MaxHandCount - (SELECT COUNT(1) FROM CurrentHand WHERE PlayerId = Player.PlayerId AND IsUsed = 0)) AS NeededHandCount
    , CardId
FROM Player, AvailableCard
WHERE Cardid IN (SELECT CardId FROM CurrentHand WHERE IsUsed = 0)
ORDER BY PlayerId

表结构如下:

Player
  - PlayerId

AvailableCard
  - CardId
  - CardValue

CurrentHand
  - PlayerId
  - CardId
  - IsUsed

非常感谢。

3 个答案:

答案 0 :(得分:1)

这非常有趣。这是我“处理”所需卡片的解决方案。请阅读代码中的表彰。这只是选择,但我相信你可以自己找出插入。查看fiddle

-- for each card in player's hand assign a sequence number
with cte_currenthand as
(
  select PlayerId, 
    rank() over(partition by PlayerId order by CardId) CardSeq
  from CurrentHand
  where IsUsed = 0
)
-- for each player generate a sequence 1..10
, cte_maxhand as
(
select p.PlayerId, x.seq
from Player p
cross join (values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10)) x(seq)
)
-- get cards the players need and assign them new sequence numbers
-- basically cte_maxhand minus cte_currenthand
, cte_needed as
(
  select mh.PlayerId, row_number() over(order by mh.seq) seq
  from cte_maxhand mh
  left join cte_currenthand ch 
    on ch.CardSeq = mh.seq
    and ch.PlayerId = mh.PlayerId
  where ch.CardSeq is null
)
-- generate a random sequence on remaining cards
, cte_deal as
(
  select CardId, row_number() over(order by CHECKSUM(NewId())) seq
  from AvailableCard ac 
  where not exists (
    select *
    from CurrentHand ch
    where ch.CardId = ac.CardId
    )
)
-- deal the cards
select n.PlayerId, d.CardId
from cte_needed n
inner join cte_deal d on d.seq = n.seq

答案 1 :(得分:0)

示例表结构:

CREATE TABLE [dbo].[cards](
    [player] [nvarchar](20) NOT NULL,
    [number] [int] NOT NULL
    )

示例数据:

insert into cards values ('p1',3)
insert into cards values ('p2',5)
insert into cards values ('p3',4)
insert into cards values ('p4',2)

插入:

insert into cards
select player,10-sum(number) as number
from cards
group by player

答案 2 :(得分:0)

DECLARE @MaxHandCount int
SET @MaxHandCount = 10

SELECT Player.PlayerId
    , Count(CardID) AS CurrentHandCount
    , @MaxHandCount - Count(CardID)  AS NeededHandCount
    , CardId
FROM Player
join CurrentHead on Player.PlayerID = CurrentHead.PlayerID
WHERE IsUsed = 0
Group by Player.PlayerID
ORDER BY PlayerId