DECLARE @id varchar(8) --需要查询的协议客户id set @id= '99000009' --不查询外卖单的记录 --查询的时间范围 DECLARE @begin varchar(10) set @begin = '2020-01-01' DECLARE @end varchar(10) set @end = '2024-01-30' SELECT F_ID, F_ProcolComID, F_OrderId, F_GuaZhang, MoneyType, F_ProcolNumber, F_DateTime, F_System, F_Operationer, F_Company, F_ErMarkClient, F_LinkMan, F_Payfid, F_GroupNumber, F_PayName FROM (SELECT Gz.F_ID, Gz.F_ProcolComID, Gz.F_OrderId, Gz.F_GuaZhang, (CASE WHEN Gz.F_GuaZhang >= 0 THEN '预付' ELSE '挂账' END) AS MoneyType, Pl.F_ProcolNumber, SUBSTRING(CONVERT(varchar(19), Gz.F_DateTime, 120), 3, 14) AS F_DateTime, Gz.F_System, Gz.F_Operationer, Pl.F_Company, Gz.F_ErMarkClient, Pl.F_LinkMan, Gz.F_Payfid, ISNULL(ro.F_GroupNumber, ISNULL(Gz.F_OrderId, Gz.F_Payfid)) AS F_GroupNumber, ISNULL(pif.F_PayName, '未知/会员独立库') AS F_PayName FROM T_RecGuaZhang AS Gz LEFT OUTER JOIN T_RoomOrder AS ro ON Gz.F_OrderId = ro.F_ID INNER JOIN T_Procol AS Pl ON Gz.F_ProcolComID = Pl.F_ID LEFT OUTER JOIN T_PayInfo AS pif ON Gz.F_Payfid = pif.F_ID WHERE (Gz.F_MmOrPc = 'Procol') AND (pif.F_ProcolFid = @id) AND (CONVERT(varchar(10), Gz.F_DateTime, 23) BETWEEN @begin AND @end) AND (pif.F_PayName = '协议账户支付') AND (Gz.F_ErMarkClient NOT LIKE '%外卖单%') OR (CONVERT(varchar(10), Gz.F_DateTime, 23) BETWEEN @begin AND @end) AND (ISNULL(Gz.F_MmOrPc, '') = '')) AS a WHERE (F_GroupNumber NOT IN (SELECT ro_1.F_GroupNumber FROM (SELECT rotmp.F_ID, rotmp.F_BeginDateTime, rotmp.F_EndDateTime, rotmp.F_GroupNumber, rotmp.F_GuestType, rotmp.F_GuestLead, rotmp.F_GetMoney, rotmp.F_MemOrProType, rotmp.F_PayMent, rotmp.F_Cashier, rotmp.F_ProcolId, rotmp.F_ProPreid, rotmp.F_PM_UPS FROM T_RoomOrder AS rotmp INNER JOIN (SELECT DISTINCT rot1.F_GroupNumber FROM T_RoomOrder AS rot1 INNER JOIN T_PayInfo AS pt1 ON rot1.F_ID = pt1.F_OrderId AND pt1.F_PayType = '非现金类' AND pt1.F_PayName = '协议账户支付' AND pt1.F_ProcolFid = @id) AS rogn ON rotmp.F_GroupNumber = rogn.F_GroupNumber AND CONVERT(varchar(10), rotmp.F_EndDateTime, 23) >= @begin AND CONVERT(varchar(10), rotmp.F_EndDateTime, 23) <= @end) AS ro_1 INNER JOIN T_PriceList AS pl ON ro_1.F_ID = pl.F_RoomOrderID LEFT OUTER JOIN (SELECT F_OrderId, F_ProcolFid FROM T_PayInfo WHERE (F_Values <> 0) AND (F_PayType = '非现金类') AND (F_PayName = '协议账户支付') AND (F_ProcolFid = @id)) AS rz ON ro_1.F_ID = rz.F_OrderId GROUP BY ro_1.F_GroupNumber))