Trying to sum a joined subquery - sql-server

For my sql class I am trying to write a query that sums a column in a sub query. The Sub query has a calculated value in it and I am trying to total that calculated value for particular zipcodes.
the query runs without errors but the output is null in the sum column
Tried running the sub query on its own and the value is calculated for the column properly
select c.CustomerState
,c.CustomerZip
,sum (b.TotalSales)as Sales
from [DBM460LearningTeam].[dbo].[TBLcustomer]as c
Left Join (select v.CustomerNumber
,sum (v.QuantitySold * i.ItemPrice) as TotalSales
from TBLinvoice as v
inner join TBLitem as i
on v.ItemNumber = right(i.ItemNumber,3)
group by v.CustomerNumber) as b
on c.CustomerNumber = b.CustomerNumber
group by c.CustomerZip , c.CustomerState;
I want to sum the total sales by zipcode so i expect to see column for zipcode and column for state and column for sales and thats what I get but the sales column is Null all the way down.

Your CustomerNumbers aren't lining up on your join on. I would verify that that part if you say you have a value for TotalSales when you just run the subquery. I bet if you changed that left join to an inner join you would get nothing. So you are getting all values from TBLCustomer but nothing matches on customernumber when you do the left join.

Related

How to get column value of join query in SSRS?

I have select join query for generating report in SSRS. Query is working fine in SQL Server but as I add same query as dataset in SSRS and try to get rows count using CountRows() function it always return 0 (Zero). I'm not getting where my query is going wrong.
SQL Query
SELECT PR.NAME
FROm innovator.PROJECT PR
INNER JOIN innovator.PROJECT_RISK LPR ON LPR.SOURCE_ID = Pr.ID
INNER JOIN innovator.RISK_MANAGEMENT LR ON LR.id = LPR.RELATED_ID
Inner join innovator.PROGRAM_PROJECT P ON PR.ID = P.RELATED_ID
Inner Join innovator.PROGRAM PP ON P.SOURCE_ID = PP.ID
WHERE pp.ID = #Id
Fetching total count using CountRows() for Textbox
=CountRows(Fields!NAME.Value, "DataSetRisk")
DataSetRisk is Dataset name and Name is column name of Project Table
Use the CountRows function. For example
=CountRows("MyDataset")
Example : =CountRows("DataSetRisk")
will give you the number of rows in MyDataSet.
Try something a little simpler: Count(Fields!NAME.Value) as a column. This assumes, of course, that field name actually is populated. If the column is in separate groups, it will provide a count for each group, otherwise it will count for the entire report.

Summing a total from multiple sales into a single column

I'm having issues with what I believe should be a simple problem in SQL Server 2017. I need to show the total sales price for a given sale. This is what I have written (note I deleted the totalprice sum formulae because it returned an error) :
USE [Antiques]
GO
DECLARE #TotalPrice INT
SELECT
Sales.SaleNo,
Sales.SalesDate,
Customers.FirstName,
Customers.LastName,
Products.Price,
#TotalPrice AS TotalPrice
FROM
Customers JOIN Sales ON Customers.CustomerID = Sales.CustomerID
JOIN SalesProducts ON Sales.SaleNo = SalesProducts.SaleNo
JOIN Products ON SalesProducts.ProductID = Products.ProductID
WHERE (Products.ProductID = SalesProducts.ProductID)
GO
This is the result:
Even if I remove the item price (which I have just put in temporarily and won't be in final code) there are still multiple lines per sale (1 for each item in the sale). Have I used the wrong joins? How can I get it looking like this:
Can anyone please tell me what I'm doing wrong? I've tried so many ways of using the Sum function and Group By and failing. (Note: this has to be a basic query and not a stored procedure unfortunately)
Actually you're not too far away. I'd move the grouping in a derived table and join that, to get the totalprice.
SELECT sales.saleno,
sales.salesdate,
customers.firstname,
customers.lastname,
x.totalprice
FROM sales
INNER JOIN customers
ON customers.customerid = sales.customerid
INNER JOIN (SELECT salesproducts.saleno,
sum(products.price) totalprice
FROM salesproducts
INNER JOIN products
ON products.productid = salesproducts.productid
GROUP BY salesproducts.saleno) x
ON x.saleno = sales.salesno;

How to select min datediff value on a record

I've got a database of contacts that have registered to attend a range of events. The database also contains a table of address information. Frequently, individual contacts have multiple address records.
I need a query that returns an individual's event booking, along with the postcode from their most recent address record (relative to the date of the event).
I'm trying to use min(DATEDIFF) in the query below, but although it's correctly calculating the date difference between the event booking and the address record creation, the query's still returning duplicate results where an individual has more than one address record.
Appreciate if anyone can please advise where I'm going wrong in the query below, or advise on a better way to obtain the result:
SELECT ep.EVENTPLACENO, ad.POSTCODE, min(DATEDIFF(dd,ep.CREATIONDATE,ad.CREATIONDATE)) as datediff
FROM EVENTPLACE as ep
LEFT OUTER JOIN EVENTMODULE as em ON em.EVENTMODULENO=ep.EVENTMODULENO
LEFT OUTER JOIN ADDRESS as ad ON ad.CONTACTNO=ep.CONTACTNO
WHERE em.EVENTMODULENO = '1111111-2222222-3333333-4444444'
GROUP BY ep.EVENTPLACENO, ad.POSTCODE
SELECT ep.EVENTPLACENO, ad.POSTCODE, min(ad.CREATIONDATE) as datediff
FROM EVENTPLACE as ep
LEFT OUTER JOIN EVENTMODULE as em ON em.EVENTMODULENO=ep.EVENTMODULENO
OUTER APPLY (SELECT TOP 1 * FROM ADDRESS ad2 WHERE ad2.CONTACTNO=ep.CONTACTNO ORDER BY DATEDIFF(dd,ep.CREATIONDATE,ad2.CREATIONDATE)) AD
WHERE em.EVENTMODULENO = '1111111-2222222-3333333-4444444'
GROUP BY ep.EVENTPLACENO, ad.POSTCODE
you can use OUTER APPLY to LEFT JOIN to the TOP 1 of a sub query - the sub query then exists for the LEFT row that you are joining to the sub query - where the sub query is a TOP 1, it will join 1 to 1 (or 1 to null if no row)

MSSQL - Join tables and return user based on value in another table column

probably a badly worded question so apologies.
I have 3 tables that I want to join together.
I have created an SQLFiddle here
What I am wanting, is to compare the MAXLINEDISCOUNT from the linkloads table to the allowed discounts in the price_escalation_bands table.
so in the data, the maxlinediscount of 40 must match the next highest discount in the price_escalation_bands table where the customer_band is the same.
so I want the result to match row 1, where it is bronze and discount is 45. should my MAXLINEDISCOUNT be greater than 45, then go to the next highest which could be 50 in this case.
when it matches, return the fk_salesman_userid field and match this to the username in the users table.
Obviously, all this data is dynamic so needs to look at next highest...
Currently, it is returning as blank so dont think my syntax is quite correct.
my query is:
select price_authorized,load_number,maxlinediscount,customer_band,[price_escalation_bands].fk_salesman_userid,Users.firstname firstname,totalcost,period,creditlimit,currentbalance,customername,totalcubes,treatedcubes,normalcubes,pricingissue from #linkloads
left outer JOIN [price_escalation_bands] on [price_escalation_bands].band=#linkloads.customer_band
AND price_escalation_bands.discount = (
SELECT top 1 [price_escalation_bands].[discount]
FROM [price_escalation_bands]
WHERE [price_escalation_bands].band=#linkloads.customer_band
AND [price_escalation_bands].[discount]<=#linkloads.maxlinediscount
ORDER BY [price_escalation_bands].[discount]
)
left outer join Users
on Users.userid=[price_escalation_bands].fk_salesman_userid
Help, appreciated as always.
This lists all price_escalation_bands entries over the matching limit in linkloads:
select u.username
, peb.band
, peb.discount
, ll.maxlinediscount
from price_escalation_bands peb
join Users u
on peb.fk_salesman_userid = u.UserID
join linkloads ll
on ll.customer_band = peb.band
where ll.maxlinediscount < peb.discount
Your SQL Fiddle example with this query.

Small ms Sql query to get the max of an id with some criteria

I want sql query to get the above result. The result is the maximum Id in TableA whose s_id in TableB has Stat=true i.e. 1.
The following does not do what I want:
select i.category_id,i.image_id,i.image_original,i.image_title,i.photographer
from images i
inner join schedule s
on i.scheduleid=s.scheduleid
and s.status='live'
where image_id=(select max(image_id) from images)
Use TOP to retrieve only 1 row
Use ORDER BY to control the sorting, so you get the single row you want
SELECT TOP(1) a.id, a.[image], a.s_id, b.stat, b.[desc]
FROM TableA a
JOIN TableB b on a.s_id = b.s_id
WHERE b.stat = 1
ORDER BY A.ID DESC
An SQLFiddle showing this.

Resources