Need the sum of two columns from subquery - sql-server

I have here my query and subquery to generate totals for the types I'm looking for in my database but now I need to somehow get the total for the entire columns. I feel like the solution is right in front of me but I cannot figure it out. Any step in the right direction would be greatly appreciated.
SELECT
SUM(b.aGiven) AS given,
SUM(b.aUsed) AS used
FROM UserAccountGroups AS uag
LEFT OUTER JOIN (
SELECT
uac1.UserAccountGroupID AS aGroupID,
SUM(ua.UserAccountUsedAmount) AS aUsed,
0 AS aGiven
FROM UserAccounts AS ua
LEFT OUTER JOIN UserAccountCodes AS uac1 ON ua.UserAccountCode = uac1.UserAccountCode
WHERE uac1.UserAccountCodeCreatedOn between '07-11-2020' and '07-11-2021'
GROUP BY uac1.UserAccountGroupID
UNION
SELECT
uac.UserAccountGroupID AS aGroupID,
0 AS aUsed,
SUM(uac.UserAccountCodeAmount) AS aGiven
FROM UserAccountCodes AS uac
LEFT OUTER JOIN UserAccounts AS ua1 ON uac.UserAccountCode = ua1.UserAccountCode
WHERE uac.UserAccountCodeCreatedOn between '07-11-2010' and '07-11-2021'
GROUP BY uac.UserAccountGroupID
) AS b ON b.aGroupID = uag.UserAccountGroupID
GROUP BY uag.ReportGroup
*** Update ***
I'm sorry if my question was unclear. This is a query I am using to pull the totals for each type of 'ReportGroup' from the db. Now, rather than needing the totals per group, I need the totals per the column. The idea is to pass in date variables in my codebehind to pull from custom dates and now I would like to have a grand total per column at the bottom of my report. I know I don't need to select any data from UserAccountGroups but I'm having trouble re-working the query to get accurate results. A point in the right direction would be very helpful and thank you beforehand.

If you can provide DML and DDL statements this could have tested easily. This will give sum for each aGroupID and grand total for columns aUsed, aGiven.
SELECT *
into #temp_agg_data
FROM
(
SELECT
uac1.UserAccountGroupID AS aGroupID,
SUM(ua.UserAccountUsedAmount) AS aUsed,
0 AS aGiven
FROM UserAccounts AS ua
LEFT OUTER JOIN UserAccountCodes AS uac1 ON ua.UserAccountCode = uac1.UserAccountCode
WHERE uac1.UserAccountCodeCreatedOn between '07-11-2020' and '07-11-2021'
GROUP BY uac1.UserAccountGroupID
UNION ALL
SELECT
uac.UserAccountGroupID AS aGroupID,
0 AS aUsed,
SUM(uac.UserAccountCodeAmount) AS aGiven
FROM UserAccountCodes AS uac
LEFT OUTER JOIN UserAccounts AS ua1 ON uac.UserAccountCode = ua1.UserAccountCode
WHERE uac.UserAccountCodeCreatedOn between '07-11-2010' and '07-11-2021'
GROUP BY uac.UserAccountGroupID
) AS A
--Last select will list down all records with sum group by [aGroupID] and grand total for [aUsed] , [aGiven] as a row below as 'Grand Total'
SELECT
[aGroupID]
,[aUsed]
,[aGiven]
FROM
#temp_agg_data
UNION ALL
SELECT
'Grand Total' AS [aGroupID]
, SUM(aUsed) as [aUsed]
, SUM(aUsed) as [aGiven]
FROM #temp_agg_data
DROP TABLE #temp_agg_data

You need to take out UserAccountGroupID in the select statements in order to get the Sum of all. Right now, you have UserAccountGroupID in the select, so it is summing by UserAccountGroupID. Hope this answers your question.

the reportGroup has not be used in the join with the subqueries so it can not be grouped by in the result query. Add the reportGroup to filter to the subqueries in the union. You don't need a union or union all sql.
declare #UserAccounts as table(UserAcccountGroupID int,UserAccountCode varchar(10),UserAccountUsedAmount money)
declare #UserAccountCodes as table (UserAccountCode varchar(10),UserAccountCodeCreatedOn Date,UserAccountGroupID int,UserAccountCodeAmount money)
declare #UserAccountGroups as table(UserAccountGroupID int,ReportGroup varchar(10));
select
IsNull(UserAccountCodes.aGiven,0) aGiven
,IsNull(UserAccounts.aUsed,0) aUsed
FROM #UserAccountGroups AS uag
OUTER APPLY
(
SELECT
--uac1.UserAccountGroupID AS aGroupID,
SUM(ua.UserAccountUsedAmount) AS aUsed
--0 AS aGiven
FROM #UserAccounts AS ua
LEFT JOIN #UserAccountCodes AS uac1
ON ua.UserAccountCode = uac1.UserAccountCode
WHERE uac1.UserAccountCodeCreatedOn between '07-11-2020' and '07-11-2021'
and uac1.UserAccountGroupID = uag.UserAccountGroupID
) UserAccounts
outer apply
(
SELECT
--uac.UserAccountGroupID AS aGroupID,
--0 AS aUsed,
SUM(uac.UserAccountCodeAmount) AS aGiven
FROM #UserAccountCodes AS uac
LEFT JOIN #UserAccounts AS ua1
ON uac.UserAccountCode = ua1.UserAccountCode
WHERE uac.UserAccountCodeCreatedOn between '07-11-2010' and '07-11-2021'
and uac.UserAccountGroupID = uag.UserAccountGroupID
) UserAccountCodes

Related

Using the results of WITH clause IN where STATEMENT of main query

I am relatively new at SQL so I apologise if this is obvious but I cannot work out how to use the results of the WITH clause query in the where statement of my main query.
My with query pulls the first record for each customer and gives the sale date for that record:
WITH summary AS(
SELECT ed2.customer,ed2.saledate,
ROW_NUMBER()OVER(PARTITION BY ed2.customer
ORDER BY ed2.saledate)AS rk
FROM Filteredxportdocument ed2)
SELECT s.*
FROM summary s
WHERE s.rk=1
I need to use the date in the above query as the starting point and pull all records for each customer for their first 12 months i.e. where the sale date is between ed2.saledate AND ed2.saledate+12 months.
My main query is:
SELECT ed.totalamountincvat, ed.saledate, ed.name AS SaleRef,
ed.customer, ed.customername, comp.numberofemployees,
comp.companyuid
FROM exportdocument AS ed INNER JOIN
FilteredAccount AS comp ON ed.customer = comp.accountid
WHERE (ed.statecode = 0) AND
ed.saledate BETWEEN ed2.saledate AND DATEADD(M,12,ed2.saledate)
I am sure that I need to add the main query into the WITH clause but I cant work out where. Is anyone able to help please
Does this help?
;WITH summary AS(
SELECT ed2.customer,ed2.saledate,
ROW_NUMBER()OVER(PARTITION BY ed2.customer
ORDER BY ed2.saledate)AS rk
FROM Filteredxportdocument ed2)
SELECT ed.totalamountincvat, ed.saledate, ed.name AS SaleRef,
ed.customer, ed.customername, comp.numberofemployees,
comp.companyuid
FROM exportdocument AS ed INNER JOIN
FilteredAccount AS comp ON ed.customer = comp.accountid
OUTER APPLY (SELECT s.* FROM summary s WHERE s.rk=1) ed2
WHERE ed.statecode = 0 AND
ed.saledate BETWEEN ed2.saledate AND DATEADD(M,12,ed2.saledate)
and ed.Customer = ed2.Customer
Results of CTE are not cached or stored, so you can't reuse it.
EDIT:
Based upon your requirement that all the records from CTE should be in final result, this is a new query:
;WITH summary AS(
SELECT ed2.customer,ed2.saledate,
ROW_NUMBER()OVER(PARTITION BY ed2.customer
ORDER BY ed2.saledate)AS rk
FROM Filteredxportdocument ed2)
SELECT
ed.totalamountincvat,
ed.saledate,
ed.name AS SaleRef,
ed.customer,
ed.customername,
comp.numberofemployees,
comp.companyuid
FROM
summary ed2
left join exportdocument ed
on ed.Customer = ed2.Customer
and ed.statecode = 0
AND ed.saledate BETWEEN ed2.saledate AND DATEADD(M,12,ed2.saledate)
INNER JOIN FilteredAccount comp
ON ed.customer = comp.accountid
WHERE
s.rk=1
summary you will be able to use only once. Alternate solution is store summary into temp table and use that as many times as u want.
Something like : Select * into #temp from Summary s where s.rk=1

Duplicate record after joining two tables

I am currently having trouble with my query after joining two tables I am getting duplicated records. What i want to do is get the details from table 1 and the payment record from table 2 with same date.. here is my query.
SELECT dbo.tblautoipekonek.ipno,
dbo.tblautoipekonek.awbno,
dbo.tblautoipekonek.ipamount,
dbo.tblautoipekonek.orno,
dbo.tbladdfunds.username,
dbo.tbladdfunds.newctfbal,
dbo.tbladdfunds.addedctfamt,
dbo.tbladdfunds.oldctfbal,
dbo.tbladdfunds.newipbal,
dbo.tbladdfunds.addedipamt,
dbo.tbladdfunds.oldipbal,
dbo.tbladdfunds.date,
dbo.tblautoipekonek.date AS Expr1
FROM dbo.tblautoipekonek
LEFT OUTER JOIN dbo.tbladdfunds
ON dbo.tblautoipekonek.date = dbo.tbladdfunds.date
WHERE
( dbo.tblautoipekonek.date = '06/06/2014' )
Hi you can use "Distinct" keyword at after "select" keyword. it will get the single record.
Good to replace dbo.tablename with alias name give to tablename as
select
distinct
auto.IPNo, ... ---here you can add other column of this table.
fund.AddedCTFAmt --same thing done here.
FROM tblAutoIPEkonek auto
LEFT OUTER JOIN dbo.tblAddfunds fund
ON auto.Date = fund.Date --try to add more join condition so filteration done here of data which is fastest/
WHERE (auto.Date = '06/06/2014')
SELECT DISTINCT dbo.tblautoipekonek.ipno,
dbo.tblautoipekonek.awbno,
dbo.tblautoipekonek.ipamount,
dbo.tblautoipekonek.orno,
dbo.tbladdfunds.username,
dbo.tbladdfunds.newctfbal,
dbo.tbladdfunds.addedctfamt,
dbo.tbladdfunds.oldctfbal,
dbo.tbladdfunds.newipbal,
dbo.tbladdfunds.addedipamt,
dbo.tbladdfunds.oldipbal,
dbo.tbladdfunds.date,
dbo.tblautoipekonek.date AS Expr1
FROM dbo.tblautoipekonek
LEFT OUTER JOIN dbo.tbladdfunds
ON dbo.tblautoipekonek.date = dbo.tbladdfunds.date
WHERE
( dbo.tblautoipekonek.date = '06/06/2014' )
GROUP BY dbo.tblautoipekonek.ipno,
dbo.tblautoipekonek.awbno,
dbo.tblautoipekonek.ipamount,
dbo.tblautoipekonek.orno,
dbo.tbladdfunds.username,
dbo.tbladdfunds.newctfbal,
dbo.tbladdfunds.addedctfamt,
dbo.tbladdfunds.oldctfbal,
dbo.tbladdfunds.newipbal,
dbo.tbladdfunds.addedipamt,
dbo.tbladdfunds.oldipbal,
dbo.tbladdfunds.date,
dbo.tblautoipekonek.date AS Expr1
Not sure if this will work for you but this is what I would use:
SELECT
p.ipno,
p.awbno,
p.ipamount,
p.orno,
f.username,
f.newctfbal,
f.addedctfamt,
f.oldctfbal,
f.newipbal,
f.addedipamt,
f.oldipbal,
f.date,
p.date Expr1
FROM
dbo.tblautoipekonek p
CROSS APPLY
(
SELECT TOP 1
*
FROM
dbo.tbladdfunds f
WHERE
p.date = f.date
ORDER BY
f.newipbal DESC
) f
This will get you one line from each entry in dbo.tblautoipekonek joined with the matching date entry from dbo.tbladdfunds which has the highest value in newipbal

TOP And DISTINCT in one query

How can i use top and distinct in one statement i am using this but not success . I dont know what i am doing wrong .
Below is my statement that i am using but giving me exception.
SELECT TOP 30 * from
(
SELECT DISTINCT
Bill.CLIENTID,Bill.TRANDATE,Bill.TRANTYPE,Bill.DUE,Bill.AMOUNT,Bill.paid,ORDE_.INVDATE ,Bill.TRANDESC,Bill.INVNUM
FROM BILLING Bill LEFT OUTER JOIN ORDE_ ON Orde_.INVNUM = Bill.INVNUM
WHERE Bill.CLIENTID = 1047 )
Missing table alias for the subquery may be the cause of your error. You don't need a subquery, you can use both Distinct and Top together.
Top(n) records depend on the order of the result set. So don't forget to explicitly Order your results.
SELECT DISTINCT TOP(30) Bill.CLIENTID,Bill.TRANDATE,Bill.TRANTYPE,Bill.DUE,Bill.AMOUNT,
Bill.paid,ORDE_.INVDATE ,Bill.TRANDESC,Bill.INVNUM
FROM BILLING Bill LEFT OUTER JOIN ORDE_ ON Orde_.INVNUM = Bill.INVNUM
WHERE Bill.CLIENTID = 1047
ORDER BY ....
It may help
SELECT TOP 30 * from
(
SELECT DISTINCT
Bill.CLIENTID,Bill.TRANDATE,Bill.TRANTYPE,Bill.DUE,Bill.AMOUNT,Bill.paid,ORDE_.INVDATE ,Bill.TRANDESC,Bill.INVNUM
FROM BILLING Bill LEFT OUTER JOIN ORDE_ ON Orde_.INVNUM = Bill.INVNUM
WHERE Bill.CLIENTID = 1047 ) Alias

mssql query join to work out esclation person based on discounts percentage

Hi I have the below working query(mssql)
select
max(load_number) load_number,max(linediscount) maxlinediscount,max(CustomerBand) customer_band
from [Linked_Order_lines]
join [Customer_Order_Summary]
on [Customer_Order_Summary].[CustomerOrderID]=[Linked_Order_lines].[load_number]
join [Customers]
on Customers.CustomerName=Customer_Order_Summary.CustomerName
join Customer_Order_lines
on Customer_Order_Summary.CustomerOrderID=Customer_Order_lines.CustomerOrderID
join price_escalation_bands
on price_escalation_bands.band=Customer_Order_Summary.CustomerBand
where [linked_order_id] in
(
select [linkedorderid] from
[Linked_Order_Summary] join [Linked_Order_lines] on
[Linked_Order_Summary].[linkedorderid] = [Linked_Order_lines].[linked_order_id]
where [load_number]='7'
)
and Customer_Order_lines.linestatus='current'
group by load_number
This produces the result
In this query, I have already joined to the table price_escalation_bands which looks like this:
What I am wanting to do, is compare the maxlinediscount from my query with the discount column of table price_escalation_bands and return the user id (fk_salesman_userid) of the record in the table that is the next greatest. so discount of 11 would go to discount 15 and return fk_salesman_userid 9. if the discount was 18, it would go to 100 and return fk_salesman_userid 21.
I am basically trying to work out the fk_salesman_userid that can approve the discount in maxlinediscount
So desired output would be:
Do I need a case statement and if so how do I use it with the max statements in my existing select statement?
thanks in advance as aways
While joining the price_escalation_bands you can use one more condition for discount.
Check the FIDDLE. Here I have tried with the result in a temp table. You can try the same subquery with your join price_escalation_bands by passing the max(linediscount).
Hope this will help you.
Final Working syntax:
IF OBJECT_ID('tempdb..#linkloads') IS NOT NULL
BEGIN
DROP TABLE #linkloads
END
CREATE TABLE #linkloads
(
maxlinediscount [decimal](10,3),
customer_band [varchar](50),
load_number [int],
totalcost [decimal](10,3),
period [datetime],
CreditLimit[decimal](10,3),
CurrentBalance[decimal](10,3),
CustomerName [varchar](100),
TotalCubes[decimal](10,3),
TreatedCubes[decimal](10,3),
NormalCubes[decimal](10,3),
PricingIssue[bit]
);
insert into #linkloads
select max(linediscount) maxlinediscount,max(CustomerBand) customer_band,max(load_number) load_number,max(totalcost) totalcost,max(Customer_Order_Summary.PeriodStart) period,max(Customers.CreditLimit) CreditLimit ,max(Customers.CurrentBalance)CurrentBalance,max(Customer_Order_Summary.CustomerName)CustomerName,max(TotalCubes) TotalCubes,max(TreatedCubes)TreatedCubes ,max(TotalCubes-TreatedCubes) as NormalCubes,sum(case when pricingissue=1 THEN 1 ELSE 0 END) pricingissue
from [Linked_Order_lines]
join [Customer_Order_Summary]
on [Customer_Order_Summary].[CustomerOrderID]=[Linked_Order_lines].[load_number]
join [Customers]
on Customers.CustomerName=Customer_Order_Summary.CustomerName
join Customer_Order_lines
on Customer_Order_Summary.CustomerOrderID=Customer_Order_lines.CustomerOrderID
where [linked_order_id] in
(
select [linkedorderid] from
[Linked_Order_Summary] join [Linked_Order_lines] on
[Linked_Order_Summary].[linkedorderid] = [Linked_Order_lines].[linked_order_id]
where [load_number]='10'
)
and Customer_Order_lines.linestatus='current'
group by load_number;
select * from #linkloads;
select load_number,maxlinediscount,customer_band,[Salesman_Discounts_per_band].fk_salesman_userid,totalcost,period,creditlimit,currentbalance,customername,totalcubes,treatedcubes,normalcubes,pricingissue from #linkloads
left outer JOIN [Salesman_Discounts_per_band] on [Salesman_Discounts_per_band].band=#linkloads.customer_band
AND [Salesman_Discounts_per_band].[discount_allowed] = (
SELECT top 1 [Salesman_Discounts_per_band].[discount_allowed]
FROM [Salesman_Discounts_per_band]
WHERE [Salesman_Discounts_per_band].band=#linkloads.customer_band
AND [Salesman_Discounts_per_band].[discount_allowed]<=#linkloads.maxlinediscount
ORDER BY [Salesman_Discounts_per_band].[discount_allowed]
)
;

Insert Statement Error Message

Good Morning All
My boss helped me design a query where it populates 1.37 million lines of random data, he has now asked me to insert/update the results into a blank table. But for some reason I cannot get it to work.
The three columns are ArrivalDate, PitchType_Skey and Site_Skey. But when I run my query (See below) I get an error message and I don't know why. Can you help?
Msg 121, Level 15, State 1, Line 2
The select list for the INSERT statement contains more items than the insert list. The number of SELECT values must match the number of INSERT columns.
Query:
USE Occupancy
INSERT INTO Bookings (ArrivalDate, Site_Skey, PitchType_Skey)
SELECT
Time.Date, Site.Site_Skey, Site.SiteWeighting, PitchType.PitchType_Skey,
PitchType.PitchTypeWeighting,
RAND(checksum(NEWID())) * Site.SiteWeighting * PitchType.PitchTypeWeighting AS Expr1
FROM
Capacity
INNER JOIN
Site ON Capacity.Site_Skey = Site.Site_Skey
INNER JOIN
PitchType ON Capacity.PitchType_Skey = PitchType.PitchType_Skey
INNER JOIN
Time
INNER JOIN
AGKey ON Time.ArrivalDayWeighting = AGKey.[Key] ON Capacity.StartDate <= Time.Date AND Capacity.EndDate >= Time.Date
CROSS JOIN
(SELECT 0 AS col1
UNION ALL
SELECT 1 AS col1) AS aaav
WHERE
(Time.CalendarYear = 2010)
AND (RAND(checksum(NEWID())) * Site.SiteWeighting * PitchType.PitchTypeWeighting >= 1.22)
Thanks
Wayne
The error message give you the answer. You have more items in your SELECT list (6)
Time.Date
Site.Site_Skey
Site.SiteWeighting
PitchType.PitchType_Skey
PitchType.PitchTypeWeighting
RAND(checksum(NEWID())) * Site.SiteWeighting * PitchType.PitchTypeWeighting AS Expr1
Than you do in your INSERT list (3)
ArrivalDate
Site_Skey
PitchType_Skey
Either remove some columns from your SELECT list or add some to your INSERT list.
As you haven't given the complete structure of your Bookings table I can only guess that you will need to do this
USE Occupancy
INSERT INTO Bookings
(
ArrivalDate,
Site_Skey,
PitchType_Skey
)
SELECT
Time.Date,
Site.Site_Skey,
PitchType.PitchType_Skey
FROM
Capacity
INNER JOIN Site ON Capacity.Site_Skey = Site.Site_Skey
INNER JOIN PitchType ON Capacity.PitchType_Skey = PitchType.PitchType_Skey
INNER JOIN Time
INNER JOIN AGKey ON Time.ArrivalDayWeighting = AGKey.[Key] ON Capacity.StartDate <= Time.Date AND Capacity.EndDate >= Time.Date
CROSS JOIN
(
SELECT 0 AS col1
UNION ALL
SELECT 1 AS col1
) AS aaav
WHERE
Time.CalendarYear = 2010
AND (RAND(checksum(NEWID())) * Site.SiteWeighting * PitchType.PitchTypeWeighting >= 1.22)
I have found the solution and I cant believe how easy it was, I just un-ticked the boxes I didn't want on the Query Designer.

Resources