我正在尝试在分组另一列时对一列进行求和。 SQL始终如一 给了我两个单独的行。
以下是我的脚本和我的结果:
Select A.client, A.store, A.Type as 'Ticket Type', A.[bizdate] as 'DATE',
sum(cast(round(c.[Amount2],2) as decimal (20,0))) 'QTY', c.SKU, c.[DESC],
sum(cast(round(c.[Amount1],2)as decimal(20,2))) as 'Total'
From Mydatabase A inner join mydatabase.dbo.TicketHeader B on A.
[ticket] = b.[ticket] and a.[yyyymmdd] = b.[yyyymmdd]
inner join mydatabase.dbo.ticketdetail C on C.[ticketheaderid] =
b.[id] and c.[class] = a.[class]
where
A.Store = @store
and a.yyyymmdd = @yyyymmdd
and c.class <> 'balance'
and c.Subtype <> 'cancelled'
and a.type NOT IN
('SKU','Total','CASH','CHANGE','NA','TAX1','TAX2','TAX3','TAX4','CHARGE',
'Delivery Service', 'Tip')
and c.[DESC] <> 'NA'
and c.sku = '300129'
group by c.sku, c.[DESC],a.store, a.type, a.bizdate, a.client, c.[Amount2],
c.[Amount1]
order by [ticket type]
client, Store TicketType date qty SKU Description Amount
1 2404 CURBSIDE / TO GO 20170214 1 300129 Beef TACO 2.00
1 2404 DINE IN 20170214 1 300129 Beef TACO 2.00
1 2404 DINE IN 20170214 2 300129 Beef TACO 4.00
1 2404 FOODSBY 20170214 2 300129 Beef TACO 4.00
我正在尝试将DINE IN Beef TACO分组到一行,同时总结 量。
答案 0 :(得分:1)
这里有几个设计和代码问题。 Amount1和Amount2之类的东西表明可能的标准化不佳。别名A,B,C是一个坏习惯,因为它使维护方式比应该更加困难。
除了你的代码从格式化的角度来看是一团糟,使用起来很痛苦。添加一些空白区域并将您的分组放置,这应该可以正常工作。
Select A.client
, A.store
, A.Type as 'Ticket Type'
, A.[bizdate] as 'DATE'
, sum(cast(round(c.[Amount2],2) as decimal (20,0))) 'QTY'
, c.SKU
, c.[DESC]
, sum(cast(round(c.[Amount1],2)as decimal(20,2))) as 'Total'
From Mydatabase A
inner join mydatabase.dbo.TicketHeader B on A.[ticket] = b.[ticket]
and a.[yyyymmdd] = b.[yyyymmdd]
inner join mydatabase.dbo.ticketdetail C on C.[ticketheaderid] = b.[id] and c.[class] = a.[class]
where
A.Store = @store
and a.yyyymmdd = @yyyymmdd
and c.class <> 'balance'
and c.Subtype <> 'cancelled'
and a.type NOT IN
(
'SKU','Total','CASH','CHANGE','NA','TAX1','TAX2','TAX3','TAX4','CHARGE','Delivery Service', 'Tip'
)
and c.[DESC] <> 'NA'
and c.sku = '300129'
group by A.client
, A.store
, A.Type
, A.[bizdate]
, c.SKU
, c.[DESC]
order by [ticket type]