汇总字段的小计

时间:2015-06-23 16:24:45

标签: sql sql-server-2008

我理解使用汇总" hard"数字。但我有一些我需要小计并且无法弄清楚如何。我的疑问是:

SELECT entryno
,Section
, Grade, replace(replace('<feet>'' <inches>', '<feet>', Mylength / 12), '<inches>', Mylength % 12) as Mylength
, Pcs
, MyNote
, MyReason
, savedatetime
, secwgt
,(select str(sum(secwgt*pcs*MyLength),12,3) from NYS2RandomReport t2 where (t2.entryno = t.entryno)) as lbs
,(select str(sum(secwgt*pcs*MyLength/2000),12,3) from NYS2RandomReport t2 where (t2.entryno = t.entryno)) as tons
From NYS2RandomReport t
ORDER BY section, grade, mylength

并且返回:

4   W14X120 A588-B  10' 0   7           2015-04-15 12:00:00.000 8.5000      7140.000           3.570
5   W14X120 A588-B  10' 1   6           2015-04-15 12:00:00.000 8.5000      6171.000           3.086
6   W14X120 A588-B  10' 2   3           2015-04-15 12:00:00.000 8.5000      3111.000           1.556
3   W14X120 A992    10' 4   8           2015-04-15 12:00:00.000 8.5000      8432.000           4.216
1   W14X89  A992    20' 0   10  Not for sale    Cracked 2015-04-15 12:00:00.000 8.1666     19599.840           9.800
2   W14X89  A992    21' 5   4   Not for sale    Cracked 2015-04-15 12:00:00.000 8.1666      8395.265           4.198

最后两列是Lbs和Tons。我需要按节,等级列分组的那两列的小计。

这令我感到困惑。谢谢。

1 个答案:

答案 0 :(得分:1)

首先确保先进行任何汇总,然后在之后将str()转换包围起来。

(select str(sum(secwgtpcsMyLength),12,3) from NYS2RandomReport t2 where (t2.section = t.section) and (t2.grade=t.grade)) as SectionGradelbs