我需要在子查询中帮助分组。你能帮我解决这个分组问题:
select
DATEPART(wk, oh. ExportDate) as wk,
DATEPART(dw,oh.ExportDate) as day,
ro.Name,
Pallets = sum(oh.Pallets),
Box = (select count(Number) from OrderItem where ID_OrderHead = oh.Id)
from
OrderHeadPDAEvent ohpe
left outer join OrderHead oh on oh.Id = ohpe.ID_OrderHeader
left outer join Route ro on oh.ID_Route = ro.ID
where
ID_Route = '00000000-0000-0000-0000-000000000000'
and
oh.ExportDate > dbo.GetStartOfDay('2012-08-01 14:35:00.000' )
and
oh.ExportDate < dbo.GetEndOfDay('2013-08-08 14:35:00.000')
group by
oh.ExportDate, ro.Name, oh.ID
order by
DATEPART(wk, oh. ExportDate)
数据看起来像这样:
26 3 Standard - Uten rute 5 49
26 3 Standard - Uten rute 2 45
26 3 Standard - Uten rute 2 38
26 3 Standard - Uten rute 1 26
26 3 Standard - Uten rute 1 64
26 3 Standard - Uten rute 2 45
26 3 Standard - Uten rute 3 64
我想将所有行相加以仅将它们排成一行。
答案 0 :(得分:2)
试试这个 -
SELECT
DATEPART(wk, oh.ExportDate) AS wk
, DATEPART(dw, oh.ExportDate) AS day
, ro.name
, Pallets = SUM(oh.Pallets)
, Box = SUM(n)
FROM dbo.OrderHeadPDAEvent ohpe
LEFT JOIN dbo.OrderHead oh ON oh.ID = ohpe.ID_OrderHeader
LEFT JOIN dbo.[Route] ro ON oh.ID_Route = ro.ID
LEFT JOIN (
SELECT n = COUNT(number), ID_OrderHead
FROM dbo.OrderItem
GROUP BY ID_OrderHead
) t ON t.ID_OrderHead = oh.ID
WHERE ID_Route = '00000000-0000-0000-0000-000000000000'
AND oh.ExportDate BETWEEN
dbo.GetStartOfDay('2012-08-01 14:35:00.000')
AND
dbo.GetEndOfDay('2013-08-08 14:35:00.000')
GROUP BY
oh.ExportDate
, ro.name
ORDER BY wk