我的查询结果就像
我想要这样的东西(每个ustid基于srblckd列的多个和)
我用Google搜索并尝试了多种组合。我可以创建这样的查询(订单1,4)。我认为无法在SQL Server 2008 R2中进行分区]
select
max(cst.custID) as custID,
max(custname) as custname,
max(roomtype) as roomtype,
sum(srblckd) as SRBlckd
from
SlpRooms
join
EVENT on SRHdrID = EVENT.EvtID
join
CUSTT cst on EVENT.CustID = cst.CustID
join
SALPT slps on EVENT.SPID = slps.salesid
join
roomtypes on roomtypes.roomtypeid = SlpRooms.srtypeid
where
convert(varchar(10), SRDate, 120) between '2020-02-01' and '2020-02-29'
group by
SRDate, cst.custID, srtypeid
union all
select max(cst.custID) as custID,max(custname) as custname,max(roomtype) as roomtype,sum(srblckd) as SRBlckd from SlpRooms join EVENT on SRHdrID =EVENT.EvtID join CUSTT cst on EVENT.CustID=cst.CustID join SALPT slps on EVENT.SPID=slps.salesid join roomtypes on roomtypes.roomtypeid=SlpRooms.srtypeid where convert(varchar(10),SRDate, 120) between '2020-02-01' and '2020-02-29' group by SRDate ,cst.custID order by 1,4
但是这不起作用。我还可以尝试更多。请提出建议?
如评论中所述,您可以进行汇总。我个人比较喜欢只写Grouping Sets
的控件这是使用与您的数据有些相似的数据的示例:
DECLARE @Datum TABLE (Date DATE, custID INT, custname VARCHAR(100), roomtype VARCHAR(100), SRBlckd INT)
INSERT INTO @Datum
(
Date,
custID,
custname,
roomtype,
SRBlckd
)
VALUES('2-1-2020',239, 'Value1','Value1',1),
('2-1-2020',384, 'Value2','Value2',1),
('2-1-2020',384, 'Value3','Value3',75),
('2-1-2020',384, 'Value4','Value4',3),
('2-1-2020',408, 'Value5','Value5',17),
('2-1-2020',3182, 'Value6','Value6',25)
SELECT Date,
custID,
ISNULL(custname,'Total'),
roomtype,
SUM(SRBlckd )
FROM @datum
GROUP BY GROUPING SETS (
(Date, custId, CustName, roomType, SRBLCKD),
(CustID)
)