History of Available Stock in SAP B1 - tsql

How can I find what was the available stock on a specific date in the past?
I know how to get OnHand for any date in the past:
SELECT LocType, LocCode, ItemCode, SUM(InQty-OutQty) [OnHand]
From OIVL
Where DocDate <= '7/7/2017'
AND ITEMCODE = 'xyz'
Group by LocType, LocCode, ItemCode
But this does not account for what was committed. It shows what was on hand, but not what was actually available (OnHand - Committed = Available). So, how could I get to this "Available" number for dates in the past?
Thanks!

In case this helps anyone else.... here is an example of how to get your item quantity and cost history in SAP BusinessOne. Pass the date and item you want to see history for into the function. If you omit item code it returns all items.
CREATE FUNCTION [dbo].[ufnStockAndCostHistory]
(
#EndDate DATETIME, #ItemCode NVARCHAR(255) = 'All'
)
RETURNS TABLE
AS
RETURN
(
WITH Cost AS (
SELECT
OINM.TransNum,
OINM.ItemCode,
OINM.Warehouse,
OINM.Balance,
OINM.CreateDate
FROM OINM (NOLOCK)
JOIN OITM (NOLOCK) ON OITM.ItemCode = OINM.ItemCode
JOIN OITB (NOLOCK) ON OITM.ItmsGrpCod=OITB.ItmsGrpCod
WHERE OINM.CreateDate <= #EndDate
),
FinalCostByWarehouse AS (
SELECT *
FROM Cost
WHERE TransNum = (
SELECT MAX(TransNum)
FROM Cost sub
WHERE Cost.ItemCode = sub.ItemCode
AND Cost.Warehouse = sub.Warehouse)
),
Quantity AS (
SELECT
OINM.ItemCode,
OINM.Warehouse,
SUM(OINM.InQty) - SUM(OINM.OutQty) [Qty]
FROM OINM (NOLOCK)
JOIN OITM (NOLOCK) ON OITM.ItemCode = OINM.ItemCode
JOIN OITB (NOLOCK) ON OITM.ItmsGrpCod=OITB.ItmsGrpCod
WHERE OINM.CreateDate <= #EndDate
group by OINM.ItemCode, OINM.Warehouse
)
SELECT
OITW.ItemCode,
OITW.WhsCode,
c.Balance [Cost],
q.Qty [Quantity]
FROM OITW
LEFT JOIN FinalCostByWarehouse c ON OITW.ItemCode = c.ItemCode
AND OITW.WhsCode = c.Warehouse
LEFT JOIN Quantity q ON OITW.ItemCode = q.ItemCode
AND OITW.WhsCode = q.Warehouse
WHERE (OITW.ItemCode = #ItemCode
OR #ItemCode = 'All')
AND (ISNULL(c.Balance,0) > 0
OR ISNULL(q.Qty,0) > 0)
)
Usage would look like:
SELECT *
FROM ufnStockAndCostHistory('9/15/2017','B107A-12HB')

Related

View query without sub selecting T-SQL

so I'm trying to build a view query but I keep failing using only joins so I ended up with this deformation.. Any tips on how I can write this query so I don't have to use 6 subselects?
The FeeSum and PaymentSum can be null, so ideally I do not want those in my result set and I also wouldn't like results where the FeeSum and the PaymentSum are equal.
Quick note: client is the table where the clients informations are stored (name, adress, etc..)
customer has a fk on client and is kind of a shell table for the client that store more information for the client,
payment is a list of all payments a customer did,
order is a list of all orders a customer did.
The goal is to get a list where we can track which customer has open fees to pay, based on the orders. It's a legacy project so don't ask why people can order before paying :)
SELECT
cu.Id as [CustomerId]
, CASE
WHEN cl.IsPerson = 1
THEN cl.[AdditionalName] + ' ' + cl.[Name]
ELSE cl.AdditionalName
END as [Name]
, cl.CustomerNumber
, (SELECT SUM(o.Fee) FROM [publication].[Order] o WHERE o.[State] = 2 AND o.CustomerId = cu.Id) as [FeeSum]
, (SELECT SUM(p.Amount) FROM [publication].[Payment] p WHERE p.CustomerId = cu.Id) as [PaymentSum]
, (SELECT MAX(o.OrderDate) FROM [publication].[Order] o WHERE o.[State] = 2 AND o.CustomerId = cu.Id) as [LastOrderDate]
, (SELECT MAX(p.PaymentDate) FROM [publication].[Payment] p WHERE p.CustomerId = cu.Id) as [LastPaymentDate]
, (SELECT MAX(f.Created) FROM [client].[File] f WHERE f.TemplateName = 'Reminder' AND f.ClientId = cl.Id) as [LastReminderDate]
, (SELECT MAX(f.Created) FROM [client].[File] f WHERE f.TemplateName = 'Warning' AND f.ClientId = cl.Id) as [LastWarningDate]
FROM
[publication].[Customer] cu
JOIN
[client].[Client] cl
ON cl.Id = cu.ClientId
WHERE
cu.[Type] = 0
Thanks in advance and I hope I didn't do anything wrong.
Kind regards
You could rewrite the correlated subqueries to instead use joins:
SELECT
cu.Id AS [CustomerId],
CASE WHEN cl.IsPerson = 1
THEN cl.[AdditionalName] + ' ' + cl.[Name]
ELSE cl.AdditionalName END AS [Name],
cl.CustomerNumber,
o.FeeSum,
p.PaymentSum,
o.LastOrderDate,
p.LastPaymentDate,
f.LastReminderDate,
f.LastWarningDate
FROM [publication].[Customer] cu
INNER JOIN [client].[Client] cl
ON cl.Id = cu.ClientId
INNER JOIN
(
SELECT CustomerId, SUM(Fee) AS [FeeSum], MAX(OrderDate) AS [LastOrderDate]
FROM [publication].[Order]
WHERE o.[State] = 2
GROUP BY CustomerId
) o
ON o.CustomerId = cu.Id
INNER JOIN
(
SELECT CustomerId, SUM(Amount) AS [PaymentSum], MAX(PaymentDate) AS [LastPaymentDate]
FROM [publication].[Payment]
WHERE o.[State] = 2
GROUP BY CustomerId
) p
ON p.CustomerId = cu.Id
INNER JOIN
(
SELECT ClientId,
MAX(CASE WHEN TemplateName = 'Reminder' THEN Created END) AS [LastReminderDate],
MAX(CASE WHEN TemplateName = 'Warning' THEN Created END) AS [LastWarningDate]
FROM [client].[File]
GROUP BY ClientId
) f
ON f.ClientId = cl.Id
WHERE
cu.[Type] = 0;

Prompts not working correctly in Crystal Reports

I have a report which I would like to create prompts for both VENUE and DATE RANGE, and after having these prompts bring back the incorrect data, I have deleted both and tried to start again from the beginning.
To begin with, I have a Crystal Report based upon the below SQL:
To summarise the code - it uses a common table expression broken separating the query out into revenue, space and event, finally joining this together at the end.
I had to convert the data type of the 'booking date' to DATE, because the value is stored as 2018-01-01 12:00:00:00.
WITH Revenue as
(
SELECT EV200_EVENT_MASTER.EV200_EVT_ID as [Event],
Revenue =
SUM(Case
When Orddtl.ER101_PHASE = '1' and ORDDTL.ER101_COMPL_STS = 'N'
then ORDDTL.ER101_EXT_CHRG
When ORDDTL.ER101_PHASE = '5' and ORDDTL.ER101_COMPL_STS = 'N'
then ORDDTL.ER101_EXT_CHRG
Else 0
End),
SM.EV800_SPACE_DESC,
SM.EV800_SPACE_CODE
FROM EV200_EVENT_MASTER WITH (NOLOCK)
LEFT OUTER JOIN EV870_ACCT_MASTER PrimCoord WITH (NOLOCK)
ON EV200_EVENT_MASTER.EV200_ORG_CODE = PrimCoord.EV870_ORG_CODE
AND EV200_EVENT_MASTER.EV200_COORD_1 = PrimCoord.EV870_ACCT_CODE -- Event manager
LEFT OUTER JOIN EV870_ACCT_MASTER FloorMgr WITH (NOLOCK)
ON EV200_EVENT_MASTER.EV200_ORG_CODE = FloorMgr.EV870_ORG_CODE
AND EV200_EVENT_MASTER.EV200_COORD_2 = FloorMgr.EV870_ACCT_CODE -- Floor manager
LEFT OUTER JOIN EV870_ACCT_MASTER EventAccount WITH (NOLOCK)
ON EV200_EVENT_MASTER.EV200_ORG_CODE = EventAccount.EV870_ORG_CODE
AND EV200_EVENT_MASTER.EV200_CUST_NBR = EventAccount.EV870_ACCT_CODE -- The person who made the booking
LEFT OUTER JOIN EV215_EVT_TYPE WITH (NOLOCK) -- get the event type
ON EV200_EVENT_MASTER.EV200_ORG_CODE = EV215_EVT_TYPE.EV215_ORG_CODE
AND EV200_EVENT_MASTER.EV200_EVT_TYPE = EV215_EVT_TYPE.EV215_EVT_TYPE
LEFT OUTER JOIN EV130_STATUS_MASTER WITH (NOLOCK) -- this might not be necessary. Only if we want to show status = completed, etc
ON EV200_EVENT_MASTER.EV200_EVT_STATUS = EV130_STATUS_MASTER.EV130_STATUS_CODE
LEFT OUTER JOIN EV802_SPACE_BKD SPBK
ON SPBK.EV802_ORG_CODE = EV200_ORG_CODE AND SPBK.EV802_EVT_ID = EV200_EVT_ID
LEFT OUTER JOIN ER101_ACCT_ORDER_DTL ORDDTL
ON ORDDTL.ER101_ORG_CODE = EV200_EVENT_MASTER.EV200_ORG_CODE
AND ORDDTL.ER101_EVT_ID = EV200_EVENT_MASTER.EV200_EVT_ID
LEFT OUTER JOIN EV800_SPACE_MASTER SM
ON Sm.EV800_ORG_CODE = EV200_EVENT_MASTER.EV200_ORG_CODE
AND SM.EV800_SPACE_CODE = SPBK.EV802_BKD_SPACE
WHERE EV200_EVENT_MASTER.EV200_ORG_CODE = '10'
AND EV200_EVENT_MASTER.EV200_EVT_STATUS >= 30 /* only confirmed bookings */
AND EV200_EVENT_MASTER.EV200_EVT_STATUS <= 52
AND Not(EV200_EVENT_MASTER.EV200_EVT_TYPE = 'GB') -- exclude group bookings
GROUP BY EV200_EVENT_MASTER.EV200_EVT_ID,SM.EV800_SPACE_DESC,EV800_SPACE_CODE
), eventdetails as
(
SELECT EV200_EVENT_MASTER.EV200_EVT_ID as [Event],
EV215_EVT_TYP_DESC as [Event Type],
EV200_event_master.EV200_EVT_DESC,
EV200_EVENT_MASTER.EV200_PLN_ATTEND,
--EventAccount.EV870_NAME AS [Account],
PrimCoord.EV870_FIRST_NAME + ' ' + PrimCoord.EV870_LAST_NAME AS [Event Manager],
--FloorMgr.EV870_FIRST_NAME + ' ' + FloorMgr.EV870_LAST_NAME AS [Floor Manager]
EV130_STATUS_MASTER.EV130_STATUS_DESC AS 'Status'
FROM EV200_EVENT_MASTER WITH (NOLOCK)
LEFT OUTER JOIN EV870_ACCT_MASTER PrimCoord WITH (NOLOCK)
ON EV200_EVENT_MASTER.EV200_ORG_CODE = PrimCoord.EV870_ORG_CODE
AND EV200_EVENT_MASTER.EV200_COORD_1 = PrimCoord.EV870_ACCT_CODE -- Event manager
LEFT OUTER JOIN EV870_ACCT_MASTER FloorMgr WITH (NOLOCK)
ON EV200_EVENT_MASTER.EV200_ORG_CODE = FloorMgr.EV870_ORG_CODE
AND EV200_EVENT_MASTER.EV200_COORD_2 = FloorMgr.EV870_ACCT_CODE -- Floor manager
LEFT OUTER JOIN EV870_ACCT_MASTER EventAccount WITH (NOLOCK)
ON EV200_EVENT_MASTER.EV200_ORG_CODE = EventAccount.EV870_ORG_CODE
AND EV200_EVENT_MASTER.EV200_CUST_NBR = EventAccount.EV870_ACCT_CODE -- The person who made the booking
LEFT OUTER JOIN EV215_EVT_TYPE WITH (NOLOCK) -- get the event type
ON EV200_EVENT_MASTER.EV200_ORG_CODE = EV215_EVT_TYPE.EV215_ORG_CODE
AND EV200_EVENT_MASTER.EV200_EVT_TYPE = EV215_EVT_TYPE.EV215_EVT_TYPE
LEFT OUTER JOIN EV130_STATUS_MASTER WITH (NOLOCK) -- this might not be necessary. Only if we want to show status = completed, etc
ON EV200_EVENT_MASTER.EV200_EVT_STATUS = EV130_STATUS_MASTER.EV130_STATUS_CODE
WHERE EV200_EVENT_MASTER.EV200_ORG_CODE = '10'
AND EV200_EVENT_MASTER.EV200_EVT_STATUS >= 30 /* only confirmed bookings */
AND EV200_EVENT_MASTER.EV200_EVT_STATUS <= 52
AND Not(EV200_EVENT_MASTER.EV200_EVT_TYPE = 'GB') -- exclude group bookings
), spacedetails as
(
SELECT distinct
SPDTL.EV803_BKD_SPACE,
SPDTL.EV803_EVT_ID,
SM.EV800_SPACE_DESC,
CONVERT(DATE,SPDTL.EV803_BKG_DATE) as bkg_date,
spdtl.EV803_START_TIME,
spdtl.EV803_END_TIME,
SPDTL.EV803_BKG_START_TIME,
SPDTL.EV803_BKG_END_TIME,
SPDTL.EV803_USAGE,
EV800_NOTE_1 AS [VENUE]
FROM EV803_SPACE_BKD_DTL SPDTL
INNER JOIN EV800_SPACE_MASTER SM ON SPDTL.EV803_BKD_SPACE = SM.EV800_SPACE_CODE
)
select distinct eventdetails.Event,
[Event Type],
eventdetails.EV200_EVT_DESC as 'Description',
eventdetails.EV200_PLN_ATTEND as 'PAX',
eventdetails.[Event Manager],
ss.EV800_SPACE_DESC as 'Space',
ss.bkg_date as 'Booking Date',
ss.VENUE,
eventdetails.Status,
/*spacedetails.
(CASE
WHEN spacedetails.EV803_USAGE = 'IN' THEN ''
WHEN spacedetails.EV803_USAGE = 'ET' THEN 'EVENT'
WHEN spacedetails.EV803_USAGE = 'OUT' THEN 'BUMP OUT'
END) as 'Booking Type',
*/
/*this doesnt work because it will be evaluated one row at a time, and one row will not satisfy in,et,out
CAST((CASE WHEN spacedetails.ev803_usage = 'IN' THEN spacedetails.EV803_BKG_START_TIME END) as time(0)) as 'Bump in Start Time',
CAST((CASE WHEN spacedetails.ev803_usage = 'IN' THEN spacedetails.EV803_BKG_END_TIME END) as time(0)) as 'Bump in End Time',
CAST((CASE WHEN spacedetails.ev803_usage = 'ET' THEN spacedetails.EV803_BKG_START_TIME END) as time(0)) as 'Event Start Time',
CAST((CASE WHEN spacedetails.ev803_usage = 'ET' THEN spacedetails.EV803_BKG_END_TIME END) as time(0)) as 'Event End Time',
CAST((CASE WHEN spacedetails.ev803_usage = 'OUT' THEN spacedetails.EV803_BKG_START_TIME END) as time(0)) as 'Bump Out Start Time',
CAST((CASE WHEN spacedetails.ev803_usage = 'OUT' THEN spacedetails.EV803_BKG_END_TIME END) as time(0)) as 'Bump Out End Time',
*/
(
SELECT TOP(1) CAST(s.EV803_BKG_START_TIME AS time(0))
FROM spacedetails s
WHERE s.EV803_EVT_ID = ss.EV803_EVT_ID
AND s.EV803_USAGE = 'IN'
AND s.EV803_BKD_SPACE = ss.EV803_BKD_SPACE
AND s.bkg_date = ss.bkg_date
) AS 'Bump-in Start Time',
(
SELECT TOP(1) CAST(s.EV803_BKG_END_TIME AS time(0))
FROM spacedetails s
WHERE s.EV803_EVT_ID = ss.EV803_EVT_ID
AND s.EV803_USAGE = 'IN'
AND s.EV803_BKD_SPACE = ss.EV803_BKD_SPACE
AND s.bkg_date = ss.bkg_date
) AS 'Bump-in End Time',
(
SELECT TOP(1) CAST(s.EV803_BKG_START_TIME AS time(0))
FROM spacedetails s
WHERE s.EV803_EVT_ID = ss.EV803_EVT_ID
AND s.EV803_USAGE = 'ET'
AND s.EV803_BKD_SPACE = ss.EV803_BKD_SPACE
AND s.bkg_date = ss.bkg_date
) AS 'Event Start Time',
(
SELECT TOP(1) CAST(s.EV803_BKG_END_TIME AS time(0))
FROM spacedetails s
WHERE s.EV803_EVT_ID = ss.EV803_EVT_ID
AND s.EV803_USAGE = 'ET'
AND s.EV803_BKD_SPACE = ss.EV803_BKD_SPACE
AND s.bkg_date = ss.bkg_date
) AS 'Event End Time',
(
SELECT TOP(1) CAST(s.EV803_BKG_START_TIME AS time(0))
FROM spacedetails s
WHERE s.EV803_EVT_ID = ss.EV803_EVT_ID
AND s.EV803_USAGE = 'OUT'
AND s.EV803_BKD_SPACE = ss.EV803_BKD_SPACE
AND s.bkg_date = ss.bkg_date
) AS 'Bump-out Start Time',
(
SELECT TOP(1) CAST(s.EV803_BKG_END_TIME AS time(0))
FROM spacedetails s
WHERE s.EV803_EVT_ID = ss.EV803_EVT_ID
AND s.EV803_USAGE = 'OUT'
AND s.EV803_BKD_SPACE = ss.EV803_BKD_SPACE
AND s.bkg_date = ss.bkg_date
) AS 'Bump-out End Time',
revenue.revenue
from eventdetails
inner join spacedetails ss on eventdetails.Event = ss.EV803_EVT_ID
inner join Revenue on ss.EV803_EVT_ID = revenue.Event and ss.EV803_BKD_SPACE = Revenue.EV800_SPACE_CODE
I created a Dynamic Parameter on the 'Booking date' setting allow for 'range values',
but when i try to run the report (it is deployed in Ungerboeck Event Management) I only get the prompt for a non range value.
I was able to resolve this issue.
In my original query, I referenced two datetime fields, and converted one to a date (shown below) but failed to explicitly convert the second.
FIRST > CONVERT(DATE,SPDTL.EV803_BKG_DATE) as bkg_date,
SECOND > ss.bkg_date as 'Booking Date',
After making the change to convert the second to date, the prompt worked as it should have.

How to PIVOT this query and display only TOP 10 records filtered by SUM(NetWrittenPremium) DESC

In this query I cant understand what would be the proper syntax to PIVOT it by month and also display just top 10 records based on SUM(NetWrittenPremium).
;with cte_TopClasses
AS (
select
b.YearNum,
b.MonthNum,
REPLACE(ClassCode,'+','') + ' - '+ QLL.Description as Description,
SUM( Premium) as NetWrittenPremium
FROM tblCalendar b
LEFT JOIN ProductionReportMetrics prm ON b.MonthNum=Month(prm.EffectiveDate) AND b.YearNum = YEAR(EffectiveDate)
AND prm.EffectiveDate >=DateAdd(yy, -1, DATEADD(d, 1, EOMONTH(GETDATE()))) AND prm.EffectiveDate <= EOMONTH(GETDATE()) AND CompanyLine = 'Ironshore Insurance Company'
LEFT JOIN NetRate_Quote_Insur_Quote Q ON prm.NetRate_QuoteID = Q.QuoteID
LEFT JOIN NetRate_Quote_Insur_Quote_Locat QL ON Q.QuoteID = QL.QuoteID
LEFT JOIN (SELECT * FROM NetRate_Quote_Insur_Quote_Locat_Liabi nqI
JOIN ( SELECT LocationID as LocID, MAX(ClassCode) as ClCode
FROM NetRate_Quote_Insur_Quote_Locat_Liabi GROUP BY LocationID ) nqA
ON nqA.LocID = nqI.LocationID AND nqA.ClCode = nqI.ClassCode ) QLL
ON QLL.LocationID = QL.LocationID
WHERE ( b.YearNum = YEAR(GETDATE())-1 and b.MonthNum >= MONTH(GETDATE())+1 ) OR
( b.YearNum = YEAR(GETDATE()) and b.MonthNum <= MONTH(GETDATE()) )
GROUP BY b.YearNum,b.MonthNum,ClassCode, QLL.Description
)
SELECT
--TOP 10
RANK() OVER (ORDER BY NetWrittenPremium DESC) AS Rank, *
FROM cte_TopClasses
WHERE Description IS NOT NULL
ORDER BY NetWrittenPremium DESC,YearNum,MonthNum
The result should look something like that:
If I use the query below and then using matrics in SSRS to PIVOT it - then after grouping by Description it only displays me 2 Description.
;with cte_TopClasses
AS (
select
b.YearNum,
b.MonthNum,
REPLACE(ClassCode,'+','') + ' - '+ QLL.Description as Description,
SUM( Premium) as NetWrittenPremium
FROM tblCalendar b
LEFT JOIN ProductionReportMetrics prm ON b.MonthNum=Month(prm.EffectiveDate) AND b.YearNum = YEAR(EffectiveDate)
AND prm.EffectiveDate >=DateAdd(yy, -1, DATEADD(d, 1, EOMONTH(GETDATE()))) AND prm.EffectiveDate <= EOMONTH(GETDATE()) AND CompanyLine = 'Ironshore Insurance Company'
LEFT JOIN NetRate_Quote_Insur_Quote Q ON prm.NetRate_QuoteID = Q.QuoteID
LEFT JOIN NetRate_Quote_Insur_Quote_Locat QL ON Q.QuoteID = QL.QuoteID
LEFT JOIN (SELECT * FROM NetRate_Quote_Insur_Quote_Locat_Liabi nqI
JOIN ( SELECT LocationID as LocID, MAX(ClassCode) as ClCode
FROM NetRate_Quote_Insur_Quote_Locat_Liabi GROUP BY LocationID ) nqA
ON nqA.LocID = nqI.LocationID AND nqA.ClCode = nqI.ClassCode ) QLL
ON QLL.LocationID = QL.LocationID
WHERE ( b.YearNum = YEAR(GETDATE())-1 and b.MonthNum >= MONTH(GETDATE())+1 ) OR
( b.YearNum = YEAR(GETDATE()) and b.MonthNum <= MONTH(GETDATE()) )
GROUP BY b.YearNum,b.MonthNum,ClassCode, QLL.Description
)
SELECT *
FROM (SELECT RANK() OVER (ORDER BY NetWrittenPremium DESC) AS Rank, *
FROM cte_TopClasses
WHERE Description IS NOT NULL) AA
WHERE AA.Rank <= 10
ORDER BY AA.NetWrittenPremium DESC, AA.YearNum, AA.MonthNum
And the result of it in SSRS matrics :
You could try something like this at the end of the query, rather than what is there now:
SELECT *
FROM (SELECT RANK() OVER (ORDER BY [Description] DESC) AS Rank, *
FROM cte_TopClasses
WHERE Description IN (SELECT [Description]
FROM (SELECT RANK() OVER (ORDER BY SUM(NetWrittenPremium) DESC) AS [Rank], [Description], SUM(NetWrittenPremium) AS total
FROM cte_TopClasses
WHERE [Description] IS NOT NULL
GROUP BY [Description]) BB
WHERE [Rank] <= 10)) AA
ORDER BY YearNum, MonthNum
This wraps the query in a SELECT, and filters the ranked results to the 10 you want.
Then use a matrix in the report to pivot the results.

Is T-SQL (2005) RANK OVER(PARTITION BY) the answer?

I have a stored procedure that does paging for the front end and is working fine. I now need to modify that procedure to group by four columns of the 20 returned and then only return the row within each group that contains the lowest priority. So when resort_id, bedrooms, kitchen and checkin (date) all match then only return the row that has the min priority. I have to still maintain the paging functionality. The #startIndex and #upperbound are parms passed into the procedure from the front end for paging. I’m thinking that RANK OVER (PARTITION BY) is the answer I just can’t quite figure out how to put it all together.
SELECT I.id,
I.resort_id,
I.[bedrooms],
I.[kitchen],
I.[checkin],
I.[priority],
I.col_1,
I.col_2 /* ..... (more cols) */
FROM (
SELECT ROW_NUMBER() OVER(ORDER by checkin) AS rowNumber,
*
FROM Inventory
) AS I
WHERE rowNumber >= #startIndex
AND rowNumber < #upperBound
ORDER BY rowNumber
Example 2 after fix:
SELECT I.resort_id,
I.[bedrooms],
I.[kitchen],
I.[checkin],
I.[priority],
I.col_1,
I.col_2 /* ..... (more cols) */
FROM Inventory i
JOIN
(
SELECT ROW_NUMBER() OVER(ORDER BY h.checkin) as rowNumber, MIN(h.id) as id
FROM Inventory h
JOIN (
SELECT resort_id, bedrooms, kitchen, checkin, id, MIN(priority) as priority
FROM Inventory
GROUP BY resort_id, bedrooms, kitchen, checkin, id
) h2 on h.resort_id = h2.resort_id and
h.bedrooms = h2.bedrooms and
h.kitchen = h2.kitchen and
h.checkin = h2.checkin and
h.priority = h2.priority
GROUP BY h.resort_id, h.bedrooms, h.kitchen, h.checkin, h.priority
) AS I2
on i.id = i2.id
WHERE rowNumber >= #startIndex
AND rowNumber < #upperBound
ORDER BY rowNumber
I would accompish it this way.
SELECT I.resort_id,
I.[bedrooms],
I.[kitchen],
I.[checkin],
I.[priority],
I.col_1,
I.col_2 /* ..... (more cols) */
FROM Inventory i
JOIN
(
SELECT ROW_NUMBER(ORDER BY Checkin) as rowNumber, MIN(id) id
FROM Inventory h
JOIN (
SELECT resort_id, bedrooms, kitchen, checkin id, MIN(priority) as priority
FROM Inventory
GROUP BY resort_id, bedrooms, kitchen, checkin
) h2 on h.resort_id = h2.resort and
h.bedrooms = h2.bedrooms and
h.kitchen = h2.kitchen and
h.checkin = h2.checkin and
h.priority = h2.priority
GROUP BY h.resort_id, h.bedrooms, h.kitchen, h.checkin, h.priority
) AS I2
on i.id = i2.id
WHERE rowNumber >= #startIndex
AND rowNumber < #upperBound
ORDER BY rowNumber

set value from select for few select

I have select, iside select have 2 column. This column must be filled from same select, but I don't want use select twice for it. Is it possoble use select 1 time and after that set second column value from first?
Example:
insert into #temptable from
select
a = (select aa from table1 where quantity > 5)
b = (select aa from table1 where quantity > 5)
I need:
insert into #temptable from
select
a = (select aa from table1 where quantity > 5)
b = {value from a}
Update. I wrote bad example, I need set to BalancePrediction1 and BalancePrediction2 value from Balance
INSERT #tmpBalances
SELECT PA.ContractId AS 'ContractId',
Con.Name AS 'ContractName',
Bal.PortfolioAccountId AS 'PortfolioAccountId',
PA.Name AS 'PortfolioAccountName',
RA.GeneralId AS 'RegisterAccountGeneralId',
Bal.BalanceTypeId AS 'BalanceTypeId',
Bt.Name AS 'BalanceTypeName',
Bt.Type AS 'BalanceTypeType',
Bal.BalanceTimeType AS 'BalanceTimeType',
Bal.InstrumentId AS 'InstrumentId',
Ins.Name AS 'InstrumentName',
Ins.GeneralId AS 'InstrumentGeneralId',
(Bal.Balance -
(
SELECT COALESCE(SUM(Mov.Amount), 0)
FROM trd.Movements AS Mov
WHERE
Bal.InstrumentId = Mov.InstrumentId AND
Bal.PortfolioAccountId = Mov.PortfolioAccountId AND
Bal.BalanceTypeId = Mov.BalanceTypeId AND
Bal.BalanceTimeType = Mov.BalanceTimeType AND
DateDiff(DAY, #Date, Mov.Date) > 0 AND
-- Currency může být null a NULL = NULL nejde
COALESCE(Bal.CurrencyId, -1) = COALESCE(Mov.CurrencyId, -1)
)
) as Balance,
Balance AS 'BalancePrediction1',
Balance AS 'BalancePrediction2',
Bal.CurrencyId AS 'CurrencyId',
Ccy.Code AS 'CurrencyCode',
PA.PositionServiceType 'PositionServiceType',
Ccy.Name 'CurrencyName',
S.Nominal AS 'Nominal',
S.NominalCurrencyId AS 'NominalCurrencyId',
trd.GetCurrencyCode(S.NominalCurrencyId) AS 'NominalCurrencyCode'
FROM trd.Balances AS Bal
JOIN trd.PortfolioAccounts AS PA ON PA.Id = Bal.PortfolioAccountId
JOIN trd.Contracts AS Con ON Con.Id = PA.ContractId
JOIN trd.RegisterAccounts AS RA ON RA.Id = PA.RegisterAccountId
JOIN trd.BalanceTypes AS Bt ON Bt.Id = Bal.BalanceTypeId
JOIN trd.Instruments AS Ins ON Ins.Id = Bal.InstrumentId
LEFT OUTER JOIN trd.Currencies AS Ccy ON Ccy.Id = Bal.CurrencyId
LEFT JOIN trd.SecuritiesView S ON s.Id = Ins.Id AND DateDiff(d, S.ValidFrom, #Date) >= 0 AND (S.ValidTo IS NULL OR DateDiff(d, S.ValidTo, #Date) < 0)
AND S.InstrumentInstrumentTypePriceUnit = 1
You could do an update to the table variable after the insert.
update #tmpBalances
set BalancePrediction1 = Balance,
BalancePrediction2 = Balance
Or you can use cross apply to calculate the sum.
INSERT #tmpBalances
SELECT PA.ContractId AS 'ContractId',
Con.Name AS 'ContractName',
Bal.PortfolioAccountId AS 'PortfolioAccountId',
PA.Name AS 'PortfolioAccountName',
RA.GeneralId AS 'RegisterAccountGeneralId',
Bal.BalanceTypeId AS 'BalanceTypeId',
Bt.Name AS 'BalanceTypeName',
Bt.Type AS 'BalanceTypeType',
Bal.BalanceTimeType AS 'BalanceTimeType',
Bal.InstrumentId AS 'InstrumentId',
Ins.Name AS 'InstrumentName',
Ins.GeneralId AS 'InstrumentGeneralId',
(Bal.Balance - Mov.SumAmount) AS Balance,
(Bal.Balance - Mov.SumAmount) AS 'BalancePrediction1',
(Bal.Balance - Mov.SumAmount) AS 'BalancePrediction2',
Bal.CurrencyId AS 'CurrencyId',
Ccy.Code AS 'CurrencyCode',
PA.PositionServiceType 'PositionServiceType',
Ccy.Name 'CurrencyName',
S.Nominal AS 'Nominal',
S.NominalCurrencyId AS 'NominalCurrencyId',
trd.GetCurrencyCode(S.NominalCurrencyId) AS 'NominalCurrencyCode'
FROM trd.Balances AS Bal
JOIN trd.PortfolioAccounts AS PA ON PA.Id = Bal.PortfolioAccountId
JOIN trd.Contracts AS Con ON Con.Id = PA.ContractId
JOIN trd.RegisterAccounts AS RA ON RA.Id = PA.RegisterAccountId
JOIN trd.BalanceTypes AS Bt ON Bt.Id = Bal.BalanceTypeId
JOIN trd.Instruments AS Ins ON Ins.Id = Bal.InstrumentId
LEFT OUTER JOIN trd.Currencies AS Ccy ON Ccy.Id = Bal.CurrencyId
LEFT JOIN trd.SecuritiesView S ON s.Id = Ins.Id AND DateDiff(d, S.ValidFrom, #Date) >= 0 AND (S.ValidTo IS NULL OR DateDiff(d, S.ValidTo, #Date) < 0)
AND S.InstrumentInstrumentTypePriceUnit = 1
CROSS APPLY (SELECT COALESCE(SUM(Mov.Amount), 0)
FROM trd.Movements AS Mov
WHERE
Bal.InstrumentId = Mov.InstrumentId AND
Bal.PortfolioAccountId = Mov.PortfolioAccountId AND
Bal.BalanceTypeId = Mov.BalanceTypeId AND
Bal.BalanceTimeType = Mov.BalanceTimeType AND
DateDiff(DAY, #Date, Mov.Date) > 0 AND
-- Currency může být null a NULL = NULL nejde
COALESCE(Bal.CurrencyId, -1) = COALESCE(Mov.CurrencyId, -1)
) Mov(SumAmount)
SELECT aa AS a, aa AS b
FROM table1
WHERE quantity > 5
One way;
;with T (value) as (
select aa from table1 where quantity > 5
)
insert into #temptable
select value, value from T