using WHERE clause in INSERT trigger SQL - sql-server

I am trying to insert a sum of prices from another table.
INSERT INTO Invoice_Of_Supplier (OrderSupplierID, PaymentStatus, Cost)
VALUES (
( SELECT OrderSupplierID FROM inserted),
0,
(SELECT SUM([Price(RUB)]) FROM Car
JOIN OrderOfSupplier_Car AS osc ON osc.CarID=Car.CarID
where osc.OrderSupplierID = (select OrderSupplierID from inserted)))
I have a Car table with fields price , CarID etc;
Order_Of_Supplier table with fields OrderSupplierID, SupplierID;
And Order_Of_Supplier_Car table in which there is a number of cars for each order( fields are CarID, OrderSupplierID)
I need to insert a row in table 'InvoiceOfSupplier' with fields 'OrderSupplierID', PaymentStatus and Cost.
OrderSupplierID and PaymentStatus are ok, but Cost is NULL and I cant understand why.
When i change on osc.OrderSupplierID = 2(getting OrderSupplierID directly) it doesn't work niether.
it Only works, when i remove all conditions like 'WHERE', but in this case it gets the 'Price(RUB)' of all orders, not the one I need.
EDIT:
The problem is that at the moment data was inserted in Order_Of_Supplier there was no data in Order_Of_Supplier_Car.

Try something like this:
INSERT INTO Invoice_Of_Supplier (OrderSupplierID, PaymentStatus, Cost)
VALUES (
( SELECT OrderSupplierID FROM inserted),
0,
(SELECT SUM(column_name) FROM Car
where Car.CarID = OrderOfSupplier_Car.CarID
and OrderOfSupplier_Car.OrderSupplierID in (select OrderSupplierID from inserted))

Why don't you just select from inserted?
INSERT INTO dbo.Invoice_Of_Supplier (OrderSupplierID, PaymentStatus, Cost)
SELECT
i.OrderSupplierID,
0,
SUM(osc.[Price(RUB)])
FROM inserted i
inner join dbo.OrderOfSupplier_Car osc
on osc.OrderSupplierID = i.OrderSupplierID
inner join dbo.Car c
ON c.CarID = osc.CarID
group by i.OrderSupplierID
and I reckon you don't need that join to Car at all
Some questions to you: is this after or instead of trigger? On which table is it?

Related

MSSQL: Select max date when a specific column was updated

I need to return the last records which had a certain column updated.
The data is stored in 2 tables: ClientInfo and ClientInfoHistory both of them with a large amount of data, especially the history one (which keeps track on any changes on the main table ClientInfo). Even if only one column was updated in ClientInfo, a row with the version before that update will be inserted into ClientInfoHistory with audit info (the user and the date when that row was updated).
So I am interested in returning the max date when the Flag3 was changed for each ClientID + the user who changed that and the value of Flag3
The entire script should be in a stored proc avoiding perf issues.
My idea:
I create a temp table with the entire customer's history + actual data, then I compare the Flag3 to see when that flag was changed for each customer and throw it into another temp table along with the modifiedbyuserid and modifieddate. Then I select max(modifiedDate) for each customer.
The tables look like this:
create table dbo.ClientInfo(
ClientID int,
Flag1 bit,
Flag2 bit,
Flag3 bit,
CreatedByUserID int not null,
CreatedDate datetime not null default getdate(),
ModifiedByUserID int not null,
ModifiedDate datetime not null default getdate(),
constraint PK_UserInfo primary key (ClientID)
)
create table dbo.ClientInfoHistory(
ClientInfoHistoryID bigint identity not null,
ClientID int,
Flag1 bit,
Flag2 bit,
Flag3 bit,
CreatedByUserID int not null,
CreatedDate datetime not null,
HistoryStartModifiedByUserID int not null,
HistoryStartDate datetime not null,
HistoryEndModifiedByUserID int not null,
HistoryEndDate datetime not null,
constraint PK_ClientInfoHistory primary key (ClientInfoHistoryID)
)
CREATE NONCLUSTERED INDEX ix_ClientInfoHistory_ClientID_HistoryDates
on dbo.ClientInfoHistory (ClientID, HistoryStartDate, HistoryEndDate)
The temp table with the entire customer's history + actual data contains this:
SELECT c.ClientID
,c.Flag3
,c.ModifiedDate as HistoryStartDate
,'9999-12-31' as HistoryEndDate
,c.ModifiedByUserId as HistoryStartModifiedByUserID
FROM dbo.ClientInfo c with (nolock)
UNION
SELECT
ch.ClientID
,ch.Flag3
,ch.HistoryStartDate
,ch.HistoryEndDate
,ch.HistoryStartModifiedByUserID
FROM dbo.ClientInfoHistory ch with (nolock)
insert into dbo.ClientInfo (ClientID, Flag1, Flag2, Flag3, CreatedByUserID, CreatedDate, ModifiedByUserID, ModifiedDate)
values
(1,0,0,1,1234,'2019-05-29 04:57:13.360', 1111,'2019-07-01 08:35:13.360'),
(2,0,1,0,1233,'2019-03-12 04:57:13.360', 1233, '2019-03-12 04:57:13.360')
insert into dbo.ClientInfoHistory (ClientID, Flag1, Flag2, Flag3, CreatedByUserID, CreatedDate, HistoryStartModifiedByUserID,HistoryStartDate, HistoryEndModifiedByUserID, HistoryEndDate )
values
(1,1,1,1,1234,'2019-05-29 04:57:13.360', 1234, '2019-05-29 04:57:13.360', 4321,'2019-05-31 04:57:13.360'),
(1,0,1,1,1234,'2019-05-29 04:57:13.360', 4321,'2019-05-31 04:57:13.360', 9871,'2019-06-02 06:27:13.360'),
(1,0,1,0,1234,'2019-05-29 04:57:13.360',9871,'2019-06-02 06:27:13.360', 8765,'2019-06-21 11:06:13.360'),
(1,0,0,0,1234,'2019-05-29 04:57:13.360',8765,'2019-06-21 11:06:13.360', 9871,'2019-06-22 06:27:13.360')
(1,0,0,1,1234,'2019-05-29 04:57:13.360',9871,'2019-06-22 06:27:13.360', 4321,'2019-06-25 08:35:13.360'),
(1,0,1,1,1234,'2019-05-29 04:57:13.360',4321,'2019-06-25 08:35:13.360', 1111,'2019-07-01 08:35:13.360')
So for example above...The changes of that flag are:
ClientID,Flag3,ModifiedByUserID,ModifiedDate
1, 1, 1234, 29/05/2019
1, 0, 9871, 02/06/2019
1, 1, 9871, 22/06/2019***
2, 0, 1233, 12/03/2019***
and the final set of results should return only those rows marked with *** (the last version of Flag3 for each ClienID)
I am not so happy with the enitre process I chose and I am looking for another solution with a better performance. I would be really happy to hear some ideas from you guys
Following query must give you expected result
SELECT *
FROM (
SELECT *, ROW_NUMBER () OVER (PARTITION BY ch.ClientID ORDER BY ch.HistoryStartDate DESC) as Rn
FROM
(
SELECT c.ClientID
,c.Flag3
,c.ModifiedDate as HistoryStartDate
,'9999-12-31' as HistoryEndDate
,c.ModifiedByUserId as HistoryStartModifiedByUserID
-- ,ROW_NUMBER () OVER (PARTITION BY c.ClientID ORDER BY c.ModifiedDate DESC) as Rn
FROM dbo.ClientInfo c with (nolock)
UNION
SELECT
ch.ClientID
,ch.Flag3
,ch.HistoryStartDate
,ch.HistoryEndDate
,ch.HistoryStartModifiedByUserID
--,ROW_NUMBER () OVER (PARTITION BY ch.ClientID ORDER BY ch.HistoryStartDate DESC) as Rn
FROM dbo.ClientInfoHistory ch with (nolock)
) as CH
) AS T
WHERE T.Rn = 1
Your question was not exactly clear, but I believe this is what you are looking for.
You will probably want to change your indexing around a little to include Flag3, and depending on the size of your data you might consider indexing the temp table. But this is a quick and dirty query to get you started
;WITH CTE AS
(select t2.ClientID, MAX(HistoryStartDate) NotMatchDate
from #ClientInfo t1
INNER JOIN #ClientInfoHistory t2 on t1.ClientID = t2.ClientID and t1.Flag3 <> t2.Flag3
GROUP BY t2.ClientID
)
select t2.ClientID, MIN(HistoryStartDate) ModifiedDate
INTO #tmpClient
from #ClientInfo t1
INNER JOIN #ClientInfoHistory t2 on t1.ClientID = t2.ClientID and t1.Flag3 = t2.Flag3
INNER JOIN CTE t3 on t3.ClientID = t1.ClientID
WHERE t2.HistoryStartDate > t3.NotMatchDate
GROUP BY t2.ClientID
SELECT t1.ClientID, t1.Flag3,t1.HistoryStartModifiedByUserID ModifiedByUserID, t1.HistoryStartDate ModifiedDate
FROM #ClientInfoHistory t1
INNER JOIN #tmpClient t2 on t1.ClientID = t2.ClientID and t1.HistoryStartDate = t2.ModifiedDate
UNION ALL
SELECT t1.ClientID, Flag3,CreatedByUserID ModifiedByUserID,CreatedDate ModifiedDate
FROM #ClientInfo t1
LEFT JOIN #tmpClient t2 on t1.ClientID = t2.ClientID
WHERE t2.ClientID IS NULL
EDIT #2: Fixed for new rows

three tables join is not giving desired output

I have three tables:
1: Station_Details (master data table)
2: RF_Details
3: WL_Details
As mention in below image.
I need a to take data from all three table in to a output table
Master data from Station_details and other data from RF and WL tables.
If RF_Details and WL_Details tables are having same station id and same DateTime then in output table both rows details will show in one row.
If DateTime are different then it will appear in different rows.
I tried this sql query but I am not getting the same output like OUTPUT Table.
select rf.StationID, st.stationname, st.state,rf.rf,rf.cum-rf,wl.wl,DataTime
from [RF_Details] rf
join [WL_Details] wl
join Station_Details st
on rf.StationID = wl.StationId and
rf.DataRecieved=wl.DataRecieved and
st.stationid =rf.stationid and
st.stationid = wl.stationid;
But it didn't give the right number of rows and output.
Please help me for the same.
You should always put the join conditions along with the join itself. Also, adding the INNER is a practice I follow to ensure no extra records are returned.
SELECT rf.StationID, st.stationname, st.state, wl.DataRecieved, wl.waterlevel1,
rf.dailyrainfall, rf.cumrainfall
FROM [RF_Details] rf
INNER JOIN [WL_Details] wl
ON rf.StationID = wl.StationId AND
rf.DataRecieved=wl.DataRecieved
INNER JOIN Station_Details st
ON st.stationid =rf.stationid AND
st.stationid = wl.stationid;
declare #station_details table(id int, station_id varchar(10),station_name varchar(10),state varchar(10))
declare #rf_details table (id int, station_id varchar(10),rf int, cum_rf int, dt dateTIME)
declare #wl_details table (id int, station_id varchar(10),wl int,dt datetime)
insert into #station_details values
(1,'DEL-NDL','NDL','DEL'),
(2,'UP-LKO','LKO','UP'),
(3,'MP-BHP','BHP','MP'),
(4,'MHR-MUM','MUM','MHR')
INSERT INTO #RF_DETAILS VALUES
(1,'DEL-NDL',42,435,'2016-06-13 05:15:00'),
(2,'UP-LKO',0,501,'2016-06-13 05:15:00'),
(3,'MP-BHP',20,350,'2016-06-13 05:15:00'),
(4,'MHR-MUM',30,200,'2016-06-13 05:15:00'),
(5,'MHR-MUM',15,100,'2016-06-14 05:15:00'),
(6,'UP-LKO',50,350,'2016-06-13 05:15:00')
INSERT INTO #WL_DETAILS VALUES
(1,'DEL-NDL',25,'2016-06-13 05:15:00'),
(2,'UP-LKO',35,'2016-06-13 05:30:00'),
(3,'MP-BHP',46,'2016-06-13 05:45:00'),
(4,'MHR-MUM',20,'2016-06-13 05:15:00'),
(5,'MHR-MUM',15,'2016-06-14 05:15:00'),
(6,'UP-LKO',60,'2016-06-13 05:15:00')
;with cte as
(
SELECT case
when rf.dt = wl.dt then 'Y'
else 'N'
end as matched,
rf.id as id,rf.station_id as stationid,rf.rf as rf , rf.cum_rf as cumrf , rf.dt as rfdt,
wl.id as wlid, wl.station_id ,wl.wl ,wl.dt as wldte,
rf.station_id as station,rf.dt as rfdte
FROM #RF_DETAILS RF
JOIN #WL_DETAILS WL ON rf.id = wl.id and RF.STATION_ID = WL.STATION_ID
)
select row_number() over (order by s.id) newid,
s.id,s.station_id,sd.station_name,sd.state,s.rf,s.cumrf,s.wl,
case
when s.srce = 'L' then s.rfdte
else s.wldte
end as 'Date'
from
(
select 'L' as srce,cte.id,cte.station_id,cte.rf,cte.cumrf, cte.wl as wl, cte.rfdte,cte.wldte from cte where cte.matched = 'Y'
union
select 'L' as srce,cte.id,cte.station_id,cte.rf,cte.cumrf, null as wl, cte.rfdte,cte.wldte from cte where cte.matched = 'N'
union all
select 'R' as srce,cte.id * 10,cte.station_id,null,null, cte.wl as wl, cte.rfdte,cte.wldte from cte where cte.matched = 'N'
) s
join #station_details sd on sd.station_id = s.station_id
order by s.id
You should redesign your database: right now you have a secondary key in RF_Details and WL_Details - DateTime. Which plays a role of a foreign key between them. Which is no good and will continue confusing you every time you need to join those table or collect corresponding data.
There should be another table like Station_Records which will store a row per every record for that station: (id, station_id, record_date_time). RF and WL rows if any should refer this table instead of referring Station_Details with station_id and one another with datetime.
With current structure you need to do full join of RF and WL to get both: matching by datetime - in same row, not matching - in separate rows.
select sd.station_name, Station_Records.*
from Station_Details sd
inner join
(
select
IsNull(rf.station_id, wl.station_id) station_id,
IsNull(rf.DataRecieved, wl.DataRecieved) DataRecieved,
rf.rf, rf.cum-rf, wl.wl
from [RF_Details] rf
full join [WL_Details] wl
on wl.station_id = rf.station_id
and wl.DataRecieved = rf.DataRecieved
) Station_Records
on Station_Records.station_ud = sd.station_id
concrete implementation may consist of OUTER APPLY or even be without any subqueries - it does not really matter currently.
Modify your table structure and you will always know all matching records:
select
sd.station_id, sd.station_name,
sr.DataRecieved
rf.rf, rf.cum-rf,
wl.wl
from Station_Details sd
inner join Station_Records sr
on sr.station_id = sd.station_id
left join RF_Details rf
on rf.record_id = sr.record_id
left join WL_Details wl
on wl.record_id = sr.record_id

SQL: Find MIN but greater than a MAX

I am working with task history and trying to find two dates attached to the same record: 1) Most recent time a task was approved (max approve); 2)The first submitted date after said approval.
Here is what I have so far:
Select
a.assn_uid,
max(b.ASSN_TRANS_DATE_ENTERED) as LastApprove,
e.LastSubmitted
FROM [PRJDEV_ProjectWebApp].[pub].[MSP_ASSIGNMENT_TRANSACTIONS] a
inner join [PRJDEV_ProjectWebApp].[pub].[MSP_ASSIGNMENT_TRANSACTIONS_COMMENTS] b
on a.ASSN_TRANS_UID = b.ASSN_TRANS_UID
join (select c.assn_uid,
min(d.ASSN_TRANS_DATE_ENTERED) as LastSubmitted
FROM [PRJDEV_ProjectWebApp].[pub].[MSP_ASSIGNMENT_TRANSACTIONS] c
inner join [PRJDEV_ProjectWebApp].[pub].[MSP_ASSIGNMENT_TRANSACTIONS_COMMENTS] d
on c.ASSN_TRANS_UID = d.ASSN_TRANS_UID
where c.ASSN_UID = '499879BC-28B2-E411-8B0A-00059A3C7A00'
and d.[ASSN_TRANS_COMMENT_TYPE_ENUM] = 0
group by c.assn_uid ) e
on e.ASSN_UID = a.ASSN_UID
where a.ASSN_UID = '499879BC-28B2-E411-8B0A-00059A3C7A00'
and b.[ASSN_TRANS_COMMENT_TYPE_ENUM] = 1
group by a.assn_uid, e.LastSubmitted
This is close, however, it gives me the first time ever that the task was submitted. I am sure that I need to use another subquery, I just dont know how to reference a column within the same result.
Here is the task history. Highlighted are the two dates I am trying to show:
I don't know that I could wade through your query in any reasonable amount of time, but to get the row after a particular row, you'd need to do something like this:
create table #submissions (
ID int,
DateAdded datetime,
SubmissionType nvarchar(100)
)
insert #submissions values
(1, '2010-01-01', 'first ever'),
(1, '2010-01-02', 'second'),
(1, '2010-01-03', 'third'),
(1, '2010-01-04', 'approve'),
(1, '2010-01-05', 'first after approve'),
(1, '2010-01-06', 'second after approve'),
(1, '2010-01-07', 'third after approve')
declare #lastApprovalDate datetime
select #lastApprovalDate = MAX(DateAdded)
from #submissions
where
SubmissionType = 'approve'
declare #firstAfterApprovalDate datetime
select #firstAfterApprovalDate = MIN(DateAdded)
from #submissions
where
DateAdded > #lastApprovalDate
select *
from #submissions
where
DateAdded = #firstAfterApprovalDate
drop table #submissions
In general, get the last approval date using MAX(), then get the first date after that date using MIN() where DateAdded > that max, and then select the row at that date. I added Top 1, just in case there happen to be multiple rows at that time. Not sure if that's possible in your data, but just to be safe.
With some help, we figured out we needed an additional min wrapped around the query.
SELECT
final.assn_uid,
final.LastApprove,
min(final.SubmissionDate) FirstSubmitted
FROM
(Select
a.assn_uid,
max(b.ASSN_TRANS_DATE_ENTERED) as LastApprove,
e.SubmittedDates SubmissionDate
FROM [PRJDEV_ProjectWebApp].[pub].[MSP_ASSIGNMENT_TRANSACTIONS] a
inner join [PRJDEV_ProjectWebApp].[pub].[MSP_ASSIGNMENT_TRANSACTIONS_COMMENTS] b
on a.ASSN_TRANS_UID = b.ASSN_TRANS_UID
join (select c.assn_uid,
(d.ASSN_TRANS_DATE_ENTERED) as SubmittedDates
FROM [PRJDEV_ProjectWebApp].[pub].[MSP_ASSIGNMENT_TRANSACTIONS] c
inner join [PRJDEV_ProjectWebApp].[pub].[MSP_ASSIGNMENT_TRANSACTIONS_COMMENTS] d
on c.ASSN_TRANS_UID = d.ASSN_TRANS_UID
where c.ASSN_UID = '499879BC-28B2-E411-8B0A-00059A3C7A00'
and d.[ASSN_TRANS_COMMENT_TYPE_ENUM] = 0
) e
on e.ASSN_UID = a.ASSN_UID
where a.ASSN_UID = '499879BC-28B2-E411-8B0A-00059A3C7A00'
and b.[ASSN_TRANS_COMMENT_TYPE_ENUM] = 1
and e.SubmittedDates > b.ASSN_TRANS_DATE_ENTERED
group by a.assn_uid, e.SubmittedDates) Final
GROUP BY
final.assn_uid,
final.LastApprove

Select 1 of 2 similar records where does not

So I have a table called 'Requests' which stores requests for holidays. I want to try extract certain records from the table (joined with others) with the parameter of the clocknumber. But, if there are two records with the same HolidayID and the last (top 1 desc) is of a certain value - we dont include that in the select!
Request Table [shortened down version of it];
http://i.stack.imgur.com/YY1Gk.png
The stored procedure im using is passed a parameter for the username and joins three other tables,
a 'Holidays' table (Stores information on the holiday from, to etc)
a 'Users' table (contains usernames etc)
a 'RequestType' table (contains the types of requests)
From the image of the table, If you imagine all of those requests belong to the same user, I would want to extract only the records with a requesttype of 1. (the requesttype 1 is holiday request and 2 is holiday cancel). But, if there is a second record with the same holidayID and a requesttype of 2, it does not include that.
So running the query, I would want to only get records with the ID 1 and 2, because the last 2 have the same Holiday ID, and the last of the 2 is with a requesttype to cancel the holiday.
Here is my attempted query;
SELECT Holidays.ID, EmployeeClockNumber, Employees.Name AS EmployeeName, HolidayStart, HolidayEnd, HalfDay, AMPM
FROM Holidays
INNER JOIN Employees ON Employees.ClockNumber = Holidays.EmployeeClockNumber
INNER JOIN Requests ON Requests.HolidayID = Holidays.ID
WHERE EmployeeClockNumber = #ClockNo
AND Requests.Accepted = 1
AND RequestTypeID = (SELECT TOP 1 Requests.ID
FROM Requests
INNER JOIN Holidays ON Holidays.ID = Requests.HolidayID
WHERE Requests.RequestTypeID = (SELECT ID FROM RequestType WHERE RequestType = 'Holiday Request')
AND Holidays.EmployeeClockNumber = #ClockNo
ORDER BY Requests.ID DESC)
ORDER BY ID DESC
Could someone point me in the right direction? Thank you
edit: ive got it working myself!
SELECT Holidays.ID, Holidays.EmployeeClockNumber, Employees.Name AS EmployeeName, Holidays.HolidayStart, Holidays.HolidayEnd, Holidays.HalfDay, Holidays.AMPM
FROM Requests
INNER JOIN Holidays ON Holidays.ID = Requests.HolidayID
INNER JOIN Employees ON Employees.ClockNumber = Holidays.EmployeeClockNumber
WHERE Holidays.EmployeeClockNumber = #ClockNo
AND Requests.Accepted = 1
AND Requests.HolidayID NOT IN (SELECT TOP 1 HolidayID
FROM Requests AS R1
WHERE R1.RequestTypeID <> (SELECT ID FROM RequestType WHERE RequestType = 'Holiday Request')
AND R1.HolidayID = Requests.HolidayID
ORDER BY R1.ID DESC)
SELECT * FROM TAB WHERE requestTypeID = 1
AND holidayID not in (SELECT HolidayID from TAB WHERE requestTypeID = 2)
I would use a partition on the select and then filter on that.
So something like
DECLARE #mtable TABLE (
ID INT
,RequestTypeId INT
,HolidayId INT
,Accepted NVARCHAR(50)
)
INSERT #mtable VALUES (1,1,1,'True')
INSERT #mtable VALUES (2,1,2,'True')
INSERT #mtable VALUES (3,1,3,'True')
INSERT #mtable VALUES (4,2,3,'True')
SELECT * FROM (
SELECT MAX(RequestTypeId) OVER (PARTITION BY HolidayID) AS MaxType
,Id
FROM #mtable
) q
WHERE q.MaxType <> 2

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]
)
;

Resources