我有一个类似的查询:
select
CONVERT(VARCHAR(7),[startdatetime],111) AS [year-month],
nm.nameLine1,
sum(datediff(hour, startdatetime, enddatetime)) as total
from srl
inner join sr on srl= sr.ServiceRequestId
inner join Name nm on(sr.clientCustomerId = nm.customerId and nm.nameTypeId = 'OFICE')
where (startdatetime >= '08-01-2011 00:00:00.000' and enddatetime <= '10-31-2011 00:00:00.000')
group by nm.nameLine1, [year-month]
order by nm.nameLine1, [year-month]
以上查询的输出是::
year-month nameLine1 total
---------- --------- -----------
2011/08 B 4
2011/09 B 7
2011/10 B 0
2011/08 E 167
2011/09 E 212
2011/10 E 131
2011/08 L 14
2011/09 L 23
2011/10 L 3
2011/08 O 18
2011/09 O 8
2011/10 O 7
2011/08 S 43
2011/09 S 60
2011/10 S 60
现在我的问题是,我应该如何在查询中为单个nameLine1total
在名为nameLine1
的其他列中获取总和。输出应该是这样的:
year-month nameLine1 total nameLine1total
---------- --------- ----------- ---------------
2011/08 B 4
2011/09 B 7
2011/10 B 0 11
2011/08 E 167
2011/09 E 212
2011/10 E 131 510
2011/08 L 14
2011/09 L 23
2011/10 L 3 40
2011/08 O 18
2011/09 O 8
2011/10 O 7 33
2011/08 S 43
2011/09 S 60
2011/10 S 60 163
答案 0 :(得分:0)
你使用的是什么样的sql - sql server,mysql等等。另外,它对你的答案无关紧要但你真的想要&lt; = 10-31-2011 00:00:00,这样数据从10月31日起不包含在您的查询中?此外,您将如何使用该查询 - 如果是报告工具,报告工具很可能比sql更容易计算它。如果在每一行都包含名称总数是可以接受的,那将更容易 - 例如如果“S”的所有三行在最后一栏中都显示“163”,那还可以吗?
答案 1 :(得分:0)
由于convert(.., .., 111)
我认为这是一个SQL Server,如果它是2005+我将使用CTE:
with cte (ym, n, total, row) as (
select *, row_number() over(partition by nameLine1 order by nameLine1, [year-month]) from (
select
convert(varchar(7),[startdatetime],111) as [year-month],
nm.nameLine1,
sum(datediff(hour, startdatetime, enddatetime)) as total
from srl
inner join sr on srl= sr.ServiceRequestId
inner join Name nm on
sr.clientCustomerId = nm.customerId and
nm.nameTypeId = 'OFICE'
where startdatetime >= '08-01-2011 00:00:00.000' and enddatetime <= '10-31-2011 00:00:00.000'
group by nm.nameLine1, [year-month]
order by nm.nameLine1, [year-month]
) t
)
select c.ym as [year-month], c.n as [nameLine1], c.total as [total], g.total as [nameLine1total]
from cte c
left join (
select max(row) as row, sum(total) as total, n
from cte group by n
) g on c.n = g.n and c.row = g.row