SQL多次使用相同的数据库项

时间:2013-01-13 15:58:23

标签: sql ms-access

表:

Value | Win
 12      3
 22      4
 44      5
 12      11

获取sum(Win)并按Value排序时,它会返回。所以所有人都以价值取胜。

Value | Win
 12      14
 22      4
 44      5

现在我不想只按Value订购,我想这样做:

返回所有奖金,其值大于10,20,30,40:

所以返回应该是:

Value | Win
 10+      23
 20+      9
 30+      5
 40+      5

这件事有可能吗?建议?

3 个答案:

答案 0 :(得分:2)

分组表有一些优点,例如:

group table

这将允许您构建:

group table2

使用:

SELECT Groups.GroupName, ta.Value
FROM Groups, ta
WHERE ta.Value Between [low] And [high]

甚至

WHERE ta.Value >= [low] 

最终确定:

SELECT GroupName, Count([Value]) , Sum(Win)
FROM (SELECT Groups.GroupName, ta.Value, ta.Win
FROM Groups, ta
WHERE ta.Value >= [low]) q
GROUP BY GroupName

一个优点是您可以通过编辑表格轻松添加和删除组。

答案 1 :(得分:2)

SELECT '10+' AS v,
SUM(IIF (myvalue>10, win)) AS w
FROM mytable

UNION ALL

SELECT '20+' AS v,
SUM(IIF (myvalue>20, win)) AS w
FROM mytable

UNION ALL

SELECT '30+' AS v,
SUM(IIF (myvalue>30, win)) AS w
FROM mytable

UNION ALL

SELECT '40+' AS v,
SUM(IIF (myvalue>40, win)) AS w
FROM mytable

注意:我使用的字段名称与问题中使用的名称略有不同...

答案 2 :(得分:1)

在大多数数据库中,您将使用案例陈述:

select (case when value >= 40 then '40+'
             when value >= 30 then '30+'
             when value >= 20 then '20+'
             when value > 10 then '10+'
         end)

不幸的是,MS-Access不支持这种情况,因此您必须使用iif代替:

最简单的方法是将表达式放在子查询中:

select valuegroup, sum(win)
from (select t.*,
             iif(value > 40, '40+',
                 iif(value > 30, '30+',
                     iif(value > 20, '20+',
                         iif(value > 10, '10+', '<10'
                 )))) as valuegroup
      from t
     ) t
group by valuegroup

要获得一笔运行金额,您需要进行自我加入。傻,但Access没有窗口功能:

select valuegroup, sum(cumwin)
from (select t.*, sum(t2.win) as cumwin,
             iif(t.value > 40, '40+',
                 iift.(value > 30, '30+',
                     iif(t.value > 20, '20+',
                         iif(t.value > 10, '10+', '<10'
                 )))) as valuegroup
      from t join
           t t2
           on t.value <= t2.value
      group by t.value
     ) t
group by valuegroup

如果MS Access不允许您将valuegroup放在外部查询的group by中,那么您必须输入整个表达式。