如何使用where子句遍历表的数据

时间:2013-02-25 23:43:11

标签: tsql loops

我有以下数据库和查询:

CREATE TABLE table1
    (`group` int, `points` int)
;

INSERT INTO table1
    (`group`, `points`)
VALUES
    (1, 115),
    (2, 125),
    (1, 105),
    (2, 000),
    (3, 005),
    (1, 020),
    (2, 005),
    (1, 010),
    (2, 005),
    (3, 030),
    (2, 000),
    (2, 055),
    (2, 100),
    (1, 020),
    (3, 055),
    (3, 055),
    (1, 005),
    (1, 010),
    (2, 025),
    (1, 035),
    (2, 100),
    (1, 120),
    (3, 140),
    (3, 105),
    (1, 065),
    (3, 025),
    (4, 015),
    (1, 005),
    (2, 010),
    (1, 130),
    (4, 040),
    (1, 055),
    (4, 020),
    (4, 060),
    (3, 010),
    (3, 105),
    (4, 125),
    (3, 000),
    (2, 005),
    (2, 010),
    (1, 115)
;

CREATE TABLE soruce1
    (`group` int)
;

INSERT INTO soruce1
    (`group`)
VALUES
    (1),
    (2),
    (3),
    (4)
;

  select s1.`group`, SUM(t1.`points`) FROM table1 as t1
    inner join soruce1 as s1
      on s1.`group` = t1.`group`
  where s1.`group` = 1
  GROUP BY s1.`group`
  ORDER BY SUM(t1.`points`) ASC;

Database and Query(SQL Fiddle Link)

如何使用where子句循环遍历source1中的所有值,而不必使用While循环,因此当它完成对组1的查询运行时,它将转移到组2,依此类推,直到结束表格,当然,选择将用于插入

这只是数据的一个示例,source1有近5000个条目

2 个答案:

答案 0 :(得分:2)

注释掉WHERE行-- where s1.group = 1,你会获得4行?这是你的意思吗?

答案 1 :(得分:1)

您可以删除where子句,查询将汇总每个组的总和。

SQL Fiddle

 select s1.[group], SUM(t1.points) FROM table1 as t1
    inner join soruce1 as s1
      on s1.[group] = t1.[group]
  --where s1.[group] = 1
  GROUP BY s1.[group]
  ORDER BY SUM(t1.points) ASC;