how do i update column (selmanufacturers_id) from the query - sql

SELECT
'S. J. & G. FAZUL ELLAHIE (PVT) LTD.' AS CompanyName,
'E - 46, S.I.T.E., KARACHI - 75700' AS CompanyAddress,
'admin' login_user, 'crm.sjg.local' selhost,
'admin' sellogin, 'sr_salereport' seltoprint,
'SALES REPORT' selreportTitle, '' selflagType,
'SI' selreportType, '' selfrmDate, '' seltoDate,
'' selfromProductId, '' selac_fromProductId_ac,
'' selbrandId, '' selcustomerId, '' selac_customerId_ac,
'' selgodownId, '' selsmId, '' selsalesmanId, '' selcity,
'' selarea, '' selorders_status, 'S' seldst,
'Invoice' selgroup1, '1' selcurrencyid, 'id' seltype,
'D' seldefUnit, '' selmanufacturers_id, 'Report' selyt0,
CAST(docTypeId as varchar(20)) + CAST(documentId as varchar(20)) groupId1,
[dbo].[ITL_DATE_TO_STRING_FOR_SORTING](refDate) groupTitle1,
'' groupId2, '' selgroup2,'' groupTitle2, *
FROM
[dbo].SR_Sale(null, null, 0, 0, 0, 0, N'', N'', 0, N'SI', 0, 0, 1, N'id', N'D') AS TR
WHERE
docType IN ('SI', 'GYM RECEIPT')

This is a general update statement
FROM dbo.SR_Sale
SET selmanufacturers_id ='xxx'
WHERE (TODO: add where-clause here to specify which row needs to be updated)

Assuming selmanufacturers_id does not exist in [dbo].SR_Sale function but contrary to products_id.
IF (OBJECT_ID('tempdb..#tmp_SR_SALE') IS NOT NULL )
BEGIN
DROP TABLE #tmp_SR_SALE
END
SELECT 'S. J. & G. FAZUL ELLAHIE (PVT) LTD.' AS CompanyName ,
'E - 46, S.I.T.E., KARACHI - 75700' AS CompanyAddress ,
'admin' login_user ,
'crm.sjg.local' selhost ,
'admin' sellogin ,
'sr_salereport' seltoprint ,
'SALES REPORT' selreportTitle ,
'' selflagType ,
'SI' selreportType ,
'' selfrmDate ,
'' seltoDate ,
'' selfromProductId ,
'' selac_fromProductId_ac ,
'' selbrandId ,
'' selcustomerId ,
'' selac_customerId_ac ,
'' selgodownId ,
'' selsmId ,
'' selsalesmanId ,
'' selcity ,
'' selarea ,
'' selorders_status ,
'S' seldst ,
'Invoice' selgroup1 ,
'1' selcurrencyid ,
'id' seltype ,
'D' seldefUnit ,
'' selmanufacturers_id ,
'Report' selyt0 ,
CAST(docTypeId AS VARCHAR(20)) + CAST(documentId AS VARCHAR(20)) groupId1 ,
[dbo].[ITL_DATE_TO_STRING_FOR_SORTING](refDate) groupTitle1 ,
'' groupId2 ,
'' selgroup2 ,
'' groupTitle2 ,
*
INTO #tmp_SR_SALE FROM [dbo].SR_Sale(NULL, NULL, 0, 0, 0, 0, N'', N'', 0, N'SI', 0, 0, 1,
N'id', N'D') AS TR
WHERE docType IN ( 'SI', 'GYM RECEIPT' )
UPDATE #tmp_SR_SALE
SET selmanufacturers_id = 'value here'
WHERE products_id = 9031
SELECT * FROM #tmp_SR_SALE

Related

How to SQL conver to dataframe

I want to convert to SQL to dataframe.\
SELECT day,
MAX(id),
MAX(if(device = 'Mobile devices with full browsers', 'mobile', 'pc')),
AVG(replace(replace(search_imprshare, '< 10%', '10'), '%', '') / 100),
REPLACE(SUBSTRING(SUBSTRING_INDEX(add_trackingcode, '_', 1), CHAR_LENGTH(SUBSTRING_INDEX(add_trackingcode, '_', 1 - 1)) + 2), add_trackingcode, '')
FROM MY_TEST_TABLE
GROUP BY day
But I can only do below that.
I don't know how to work on '???'.
df_data= df_data.groupby(['day').agg(
{
'id': np.max,
'device ' : ???,
'percent' : ???,
'tracking' : ???
}
)
How should I do it?

SQL Server - Find frequency of occurance (by row, not word) of most common words in a column

This question has been asked more than a few times, but I can't find the specific answer I need. I have a query that finds the most commonly appearing words in a column in SQL Server and lists them with the count of their appearances. The problem is that if a word appears multiple times in a row, it counts once for each appearance. I would like to only count each word once per row.
So a row with a value of "To be or not to be" would count 'to' and 'be' once each, not twice each for purposes of overall frequency.
Here is the current query, which also strips out common words such as pronouns and replaces all of the commonly occurring separators with spaces. It's a bit old so I suspect it could be a lot neater.
SELECT sep.Col Phrase, count(*) as Qty
FROM (
Select * FROM (
Select value = Upper(RTrim(LTrim(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Title, ',', ' '), '.', ' '), '!', ' '), '+', ' '), ':', ' '), '-', ' '), ';', ' '), '(', ' '), ')', ' '), '/', ' '), '&', ''), '?', ' '), ' ', ' '), ' ', ' '))))
FROM Table
) easyValues
Where value <> ''
) actualValues
Cross Apply dbo.SeparateValues(value, ' ') sep
WHERE sep.Col not in ('', 'THE', 'A', 'AN', 'WHO', 'BOOK', 'AND', 'FOR', 'ON', 'HAVE', 'YOUR', 'HOW', 'WE', 'IN', 'I', 'IT', 'BY', 'SO', 'THEIR', 'IS', 'OR', 'HE', 'OF', 'WHAT'
, 'HIM', 'HIS', 'SHE', 'HER', 'MY', 'FROM', 'US', 'OUR', 'AT', 'ALL', 'BE', 'OF', 'TO', 'YOU', 'WITH', 'THAT', 'THIS', 'WAS', 'ARE', 'THERE', 'BUT', 'HAS'
, '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'WILL', 'MORE', 'DIV', 'THAN', 'EACH', 'GET', 'ANY')
and LEN(sep.Col) > 2
GROUP By sep.Col
HAVING count(*) > 1
Appreciate any thoughts on a better way to do this while fixing the issue of repeat words.
You just need to GROUP BY twice.
First by sep.Col and Table.ID to remove duplicates in a row. Your table has some ID column, right?
Second, just by sep.Col to get the final count.
I have also rewritten your query using CTEs to make it readable. At least, for me it is more readable in this way.
WITH
easyValues
AS
(
Select
ID
,value = Upper(RTrim(LTrim(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Title, ',', ' '), '.', ' '), '!', ' '), '+', ' '), ':', ' '), '-', ' '), ';', ' '), '(', ' '), ')', ' '), '/', ' '), '&', ''), '?', ' '), ' ', ' '), ' ', ' '))))
FROM Table
)
,actualValues
AS
(
SELECT
ID
,Value
FROM easyValues
Where value <> ''
)
,SeparateValues
AS
(
SELECT
ID
,sep.Col
FROM
actualValues
Cross Apply dbo.SeparateValues(value, ' ') AS sep
WHERE
sep.Col not in ('', 'THE', 'A', 'AN', 'WHO', 'BOOK', 'AND', 'FOR', 'ON', 'HAVE', 'YOUR', 'HOW', 'WE', 'IN', 'I', 'IT', 'BY', 'SO', 'THEIR', 'IS', 'OR', 'HE', 'OF', 'WHAT'
, 'HIM', 'HIS', 'SHE', 'HER', 'MY', 'FROM', 'US', 'OUR', 'AT', 'ALL', 'BE', 'OF', 'TO', 'YOU', 'WITH', 'THAT', 'THIS', 'WAS', 'ARE', 'THERE', 'BUT', 'HAS'
, '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'WILL', 'MORE', 'DIV', 'THAN', 'EACH', 'GET', 'ANY')
and LEN(sep.Col) > 2
)
,UniqueValues
AS
(
SELECT
ID, Col
FROM
SeparateValues
GROUP BY
ID, Col
)
SELECT
Col AS Phrase
,count(*) as Qty
FROM UniqueValues
GROUP By Col
HAVING count(*) > 1
;
As far as I can tell, the STRING_SPLIT function along with CROSS APPLY can give you what you want. You can split the string based on the space delimiter, select each word distinctly, then count in an outer query. I ommitted the part where you don't select specific words for brevity.
Fiddle<>:
CREATE TABLE phrases(phrase NVARCHAR(MAX));
INSERT INTO phrases(phrase)VALUES(N'To be or not to be'),(N'this is not a phrase'),(N'And why is this not another one');
SELECT
w.value,
COUNT(*)
FROM
phrases AS p
CROSS APPLY (
SELECT DISTINCT
value
FROM
STRING_SPLIT(p.phrase,N' ')
) AS w
GROUP BY
w.value;
To achieve your requirement, you can use a FUNCTION to split a string into list of words by delimiter ' ' space. With the help of this function, you can then use some Dynamic SQL like cursor to get the final count.
First create the FUNCTION as-
Source Of code: stackoverflow
CREATE FUNCTION dbo.splitstring ( #stringToSplit VARCHAR(MAX) )
RETURNS #returnList TABLE ([Word] [nvarchar] (500))
AS
BEGIN
DECLARE #name NVARCHAR(255)
DECLARE #pos INT
WHILE CHARINDEX(' ', #stringToSplit) > 0
BEGIN
SELECT #pos = CHARINDEX(' ', #stringToSplit)
SELECT #name = SUBSTRING(#stringToSplit, 1, #pos-1)
INSERT INTO #returnList
SELECT #name
SELECT #stringToSplit = SUBSTRING(#stringToSplit, #pos+1, LEN(#stringToSplit)-#pos)
END
INSERT INTO #returnList
SELECT #stringToSplit
RETURN
END
Then use this CURSOR script to get your final output-
DECLARE #Value VARCHAR(MAX)
DECLARE #WordList TABLE
(
Word VARCHAR(200)
)
DECLARE db_cursor CURSOR
FOR
SELECT Upper(RTrim(LTrim(Replace(Replace(Replace(Replace(Replace
(Replace(Replace(Replace(Replace(Replace(Replace(Replace
(Replace(Replace(title, ',', ' '), '.', ' '), '!', ' '), '+', ' '), ':', ' '), '-', ' '), ';', ' ')
, '(', ' '), ')', ' '), '/', ' '), '&', ''), '?', ' '), ' ', ' '), ' ', ' ')))) [Value]
FROM table
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #Value
WHILE ##FETCH_STATUS = 0
BEGIN
INSERT INTO #WordList
SELECT DISTINCT Word FROM [dbo].[splitstring](#Value)
WHERE Word NOT IN ('', 'THE', 'A', 'AN', 'WHO', 'BOOK', 'AND', 'FOR', 'ON', 'HAVE', 'YOUR', 'HOW', 'WE', 'IN', 'I', 'IT', 'BY', 'SO', 'THEIR', 'IS', 'OR', 'HE', 'OF', 'WHAT'
, 'HIM', 'HIS', 'SHE', 'HER', 'MY', 'FROM', 'US', 'OUR', 'AT', 'ALL', 'BE', 'OF', 'TO', 'YOU', 'WITH', 'THAT', 'THIS', 'WAS', 'ARE', 'THERE', 'BUT', 'HAS'
, '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'WILL', 'MORE', 'DIV', 'THAN', 'EACH', 'GET', 'ANY')
AND LEN(Word) > 2
FETCH NEXT FROM db_cursor INTO #Value
END
CLOSE db_cursor
DEALLOCATE db_cursor
SELECT Word,COUNT(*)
FROM #WordList
GROUP BY Word

How to replace the IN operator with EXISTS operator, for the where clause part of the query?

WHERE (
((SERVICECOMPONENT_ID IN (123, 150, 198, 199, 290, 287, 291, 289, 288, 286, 282, 281)))
OR ((SERVICEREQUEST_ID IN (
SELECT distinct(SR.SERVICEREQUEST_ID)
FROM SERVICE_REQUEST SR,ASSIGNED_SR_PROJECTS ASP,PROJECT_RESOURCES PRS
WHERE SR.SERVICEREQUEST_ID = ASP.SERVICEREQUEST_ID
AND PRS.PROJECT_ID = ASP.PROJECT_ID
AND PRS.RESPONSIBILITY IN ('MANAGER','LEAD')
AND PRS.RESOURCE_ID =180 )) )
)
In general,
SELECT a FROM b WHERE c IN (SELECT d FROM e)
is equivalent to
SELECT a FROM b WHERE EXISTS (SELECT 1 FROM e WHERE c = d)
The SERVICEREQUEST_ID IN (subquery) part of your code example translates to:
OR EXISTS (
SELECT 1
FROM
SERVICE_REQUEST SR,
ASSIGNED_SR_PROJECTS ASP,
PROJECT_RESOURCES PRS
WHERE
SR.SERVICEREQUEST_ID = ASP.SERVICEREQUEST_ID
AND PRS.PROJECT_ID = ASP.PROJECT_ID
AND PRS.RESPONSIBILITY IN ('MANAGER', 'LEAD')
AND PRS.RESOURCE_ID = 180
AND mytable.SERVICEREQUEST_ID = SR.SERVICEREQUEST_ID
)
if you have static list of elements It's better to use "IN".... If you have a subquery and it is returning more than one value then Use Exist...
There is no Difference in Both clauses..
WHERE (
( (SERVICECOMPONENT_ID IN ( 123 , 150 , 198 , 199 , 290 , 287 , 291 , 289 , 288 , 286 , 282 , 281 )) )
OR ( (SERVICEREQUEST_ID IN ( 1952 , 2387 , 3618 , 3633 , 4178 , 4432 , 5090 , 5271 , 6068 , 6320 , 6396 , 6526 , 7162 , 7442 , 7558 , 7639 , 7688 , 8176 , 8189 , 8338 , 8460 , 8461 , 8598 , 8612 , 8628 , 8675 , 8775 , 8869 , 8886 , 8898 )) )
OR ( (REQUESTED_BY LIKE 'XXXXXXX#example.com' ) )
OR ( ( EXISTS ( SELECT count(distinct(SR.SERVICEREQUEST_ID)) FROM SERVICE_REQUEST SR,ASSIGNED_SR_PROJECTS ASP,PROJECT_RESOURCES PRS WHERE SR.SERVICEREQUEST_ID = ASP.SERVICEREQUEST_ID AND PRS.PROJECT_ID = ASP.PROJECT_ID AND PRS.RESPONSIBILITY IN ('MANAGER','LEAD') AND PRS.RESOURCE_ID =180 )) )
OR ( (STATUS_CODE LIKE 'OPEN' ) AND ( EXISTS (SELECT count(COMPONENT.CATEGORY_ID) FROM PROJECTMASTER PROJECTS, BUDGET BUDGET, CONTRACT CONTRACT,COMPONENTS COMPONENT, PROJECT_RESOURCES PROJ_RESOURCES, CATEGORY_OWNER_ASSIGNMENT CATEGORYOWNER, SERVICECATEGORYASSIGNMENT CATEGORYASSIGNMENT WHERE PROJECTS.PROJECT_ID = PROJ_RESOURCES.PROJECT_ID AND PROJECTS.BUDGET_ID = BUDGET.BUDGET_ID AND BUDGET.CONTRACT = CONTRACT.CONTRACT_ID AND CATEGORYASSIGNMENT.CONTRACT_ID = CONTRACT.CONTRACT_ID AND COMPONENT.COMPONENT_ID = CATEGORYASSIGNMENT.COMPONENT_ID AND CATEGORYOWNER.CATEGORY_ID = COMPONENT.CATEGORY_ID AND CATEGORYOWNER.USER_ID = PROJ_RESOURCES.RESOURCE_ID AND (CATEGORYOWNER.OWNER_FLAG = 'Y' OR CATEGORYOWNER.MEMBER_FLAG = 'Y') AND PROJ_RESOURCES.RESOURCE_ID = 180 AND PROJ_RESOURCES.ACTIVE_FLAG = 'Y' AND CATEGORYASSIGNMENT.ACTIVE_FLAG = 'Y' AND PROJ_RESOURCES.RESPONSIBILITY IN ('MANAGER', 'LEAD') )) )
)
read this for further clarification..
Difference between EXISTS and IN in SQL?

Subquery returned more than 1 value. This is not permitted when the subquery follows =,.. or when the subquery is used as an expression

I have this following stored procedure to make a reservation .I have not done the front end to insert the values so I use the execute stored procedure from the sql server menu to insert into the database but it gives me the subquery returned more than 1 value and 1 row affected message
ALTER PROCEDURE [dbo].[Usp_makereservation]
--roombookingdetails
#refno VARCHAR(50),
#propertyid int,
#roomtype VARCHAR(3),
#groupcode VARCHAR(30),
#companycode VARCHAR(10),
#arrivaldate DATETIME,
#arrivalplan VARCHAR(3),
#departuredate DATETIME,
#departureplan VARCHAR(3),
#createdby INT,
--roombookingguestdetails
#subsrno VARCHAR(50),
#roomno VARCHAR(30),
#guesttitle VARCHAR(30),
#lname VARCHAR(50),
#fname VARCHAR(50),
#mname VARCHAR(50),
#address VARCHAR(100),
#city VARCHAR(30),
#state VARCHAR(30),
#country INT,
#zipcode VARCHAR(50),
#telno VARCHAR(15),
#mobile VARCHAR(15),
#fax VARCHAR(50),
#gueststatus INT,
#designation VARCHAR(50),
#occupation VARCHAR(50),
#arrivalfrom VARCHAR(50),
#departureto VARCHAR(50),
#leader BIT,
#spclinstrctn VARCHAR(1000),
#checkinflg BIT,
--roombookingoccupancy
#singlebooked INT,
#singleprovisional INT,
#singleconfirmed INT,
#singlewaitlisted INT,
#doublebooked INT,
#doubleprovisional INT,
#doubleconfirmed INT,
#doublewaitlisted INT,
#triplebooked INT,
#tripleprovisional INT,
#tripleconfirmed INT,
#triplewaitlisted INT,
#quadbooked INT,
#quadprovisional INT,
#quadconfirmed INT,
#quadwaitlisted INT,
#marketsegID INT,
#businesssrcID INT,
#guestcategoryID INT,
#gueststatusID INT,
#totalpax INT,
#adultpax INT,
#childpax INT,
#infantpax INT,
#extraadultpax INT,
#extrachildpax INT,
#complementarypax INT,
#noshow INT,
#checkinrooms INT,
#checkinpax INT
AS
BEGIN
BEGIN try
BEGIN TRAN
INSERT INTO roombookingdetails
(reservationno,
srno,
refno,
propertyid,
roomtype,
groupcode,
companycode,
arrivaldate,
arrivalplan,
depaturedate,
depatureplan,
createdon,
createdby)
VALUES ((SELECT Isnull(Max(reservationno) + 1, 1)
FROM roombookingdetails),
(SELECT Isnull(Max(srno) + 1, 1)
FROM roombookingdetails),
#refno,
#propertyid,
#roomtype,
#groupcode,
#companycode,
#arrivaldate,
#arrivalplan,
#departuredate,
#departureplan,
Getdate(),
#createdby)
INSERT INTO roombookingguestdetails
(reservationno,
srno,
subsrno,
roomno,
guesttitle,
lastname,
firstname,
midname,
[address],
city,
[state],
country,
zipcode,
telno,
mobile,
fax,
gueststatus,
designation,
occupation,
arrivalfrom,
depatureto,
leader,
specialinstruction,
checkinflag,
createdon,
createdby)
VALUES ((SELECT [reservationno]
FROM roombookingdetails),
(SELECT Isnull(Max(srno) + 1, 1)
FROM roombookingguestdetails),
#subsrno,
#roomno,
#guesttitle,
#lname,
#fname,
#mname,
#address,
#city,
#state,
#country,
#zipcode,
#telno,
#mobile,
#fax,
#gueststatus,
#designation,
#occupation,
#arrivalfrom,
#departureto,
#leader,
#spclinstrctn,
#checkinflg,
Getdate(),
#createdby)
INSERT INTO roombookingoccupancy
(reservationno,
srno,
singlebooked,
singleprovisional,
singleconfirmed,
singlewaitlisted,
doublebooked,
doubleprovisional,
doubleconfirmed,
doublewaitlisted,
tripplebooked,
trippleprovisional,
trippleconfirmed,
tripplewaitlisted,
quadbooked,
quadprovisional,
quadconfirmed,
quadwaitlisted,
marketsegmentid,
businesssourceid,
guestcategoryid,
gueststatusid,
totalpax,
adultpax,
childpax,
infantpax,
extraadultpax,
extrachildpax,
complementrypax,
noshow,
checkinrooms,
checkinpax,
createdon,
createdby)
VALUES ((SELECT [reservationno]
FROM roombookingdetails),
(SELECT Isnull(Max(srno) + 1, 1)
FROM roombookingoccupancy),
#singlebooked,
#singleprovisional,
#singleconfirmed,
#singlewaitlisted,
#doublebooked,
#doubleprovisional,
#doubleconfirmed,
#doublewaitlisted,
#triplebooked,
#tripleprovisional,
#tripleconfirmed,
#triplewaitlisted,
#quadbooked,
#quadprovisional,
#quadconfirmed,
#quadwaitlisted,
#marketsegID,
#businesssrcID,
#guestcategoryID,
#gueststatusID,
#totalpax,
#adultpax,
#childpax,
#infantpax,
#extraadultpax,
#extrachildpax,
#complementarypax,
#noshow,
#checkinrooms,
#checkinpax,
Getdate(),
#createdby)
COMMIT TRAN
END try
BEGIN catch
PRINT 'Rollback'
SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_SEVERITY() AS ErrorSeverity, ERROR_STATE() AS ErrorState, ERROR_PROCEDURE() AS ErrorProcedure, ERROR_LINE() AS ErrorLine, ERROR_MESSAGE() AS ErrorMessage;
ROLLBACK
END catch
END
Here is the query generated after selecting execute stored procedure command
DECLARE #return_value int
EXEC #return_value = [dbo].[Usp_makereservation]
#refno = N'12',
#propertyid = 2,
#roomtype = N'R345',
#groupcode = N'G25',
#companycode = N'C422',
#arrivaldate = N'1/2/3',
#arrivalplan = N'fd',
#departuredate = N'5/2/3',
#departureplan = N'gdfgd',
#createdby = 1,
#subsrno = N'g',
#roomno = N'fgd',
#guesttitle = N'fdf',
#lname = N'gdf',
#fname = N'f',
#mname = N'd',
#address = N'dfg',
#city = N'fdg',
#state = N'fd',
#country = 3,
#zipcode = N'rt',
#telno = N'etr',
#mobile = N'et',
#fax = N'r',
#gueststatus = 4,
#designation = N'ertre',
#occupation = N'tert',
#arrivalfrom = N'ret',
#departureto = N'ret',
#leader = 1,
#spclinstrctn = N'er',
#checkinflg = 1,
#singlebooked = 2,
#singleprovisional = 2,
#singleconfirmed = 3,
#singlewaitlisted = 2,
#doublebooked = 23,
#doubleprovisional = 2,
#doubleconfirmed = 3,
#doublewaitlisted = 23,
#triplebooked = 23,
#tripleprovisional = 23,
#tripleconfirmed = 23,
#triplewaitlisted = 23,
#quadbooked = 2,
#quadprovisional = 3,
#quadconfirmed = 24,
#quadwaitlisted = 23,
#marketsegID = 432,
#businesssrcID = 4,
#guestcategoryID = 234,
#gueststatusID = 234,
#totalpax = 234,
#adultpax = 23,
#childpax = 4,
#infantpax = 234,
#extraadultpax = 23,
#extrachildpax = 4234,
#complementarypax = 23,
#noshow = 4,
#checkinrooms = 234,
#checkinpax = 43232
SELECT 'Return Value' = #return_value
GO
There is chanch that your following statement may returns more than single value.
Please check it.
> SELECT [reservationno] FROM roombookingdetails
You have used it in your insert statement.
You have to usewhere clause,Top operator,Min,Max,Avg in your subquery when there is such type of problem or more then 1 record exist.
Replacing this (SELECT [reservationno] FROM roombookingdetails) from first insert
with this
(SELECT Isnull(Max(reservationno) + 1, 1) FROM roombookingguestdetails)
and this (SELECT [reservationno] FROM roombookingdetails) from second insert
with this (SELECT Isnull(Max(reservationno) + 1, 1) FROM (RoomBookingOccupancy)
solved my problem

Select from select with case statement and union all

When I am executing query
SELECT Settlement_Fees.Participant_Name, Settlement_Fees.Account, Settlement_Fees.Billing_Account, Settlement_Fees.Descr1, Settlement_Fees.Market, Settlement_Fees.Instrum
--, IIf(Settlement_Fees.Instr_Type='Internal','bsinternal',Settlement_Fees.Instr_Type) AS Expr1
,(case when Settlement_Fees.Instr_Type='Internal' then 'bsinternal'
else Settlement_Fees.Instr_Type
end )
, Settlement_Fees.Country, Settlement_Fees.Nr_Instr_Business_Unit, Settlement_Fees.Nr_Instr_Account, Settlement_Fees.Avg_EUR_Rate, Settlement_Fees.Fee_Amount_EUR, Settlement_Fees.Value_Date_Adj
FROM Settlement_Fees)
union all
(select '','',Billing_Account,'','','',
( case when Instr_Type like '%Bridge%' or Instr_Type = '%Internal%' then 'Bszridge/Internal'
else Instr_Type
end )
,'','',Nr_Instr_Account ,'',Fee_Amount_EUR ,''
from Settlement_Fees group by Settlement_Fees.Billing_Account,Settlement_Fees.Instr_Type
,Settlement_Fees.Nr_Instr_Account,Fee_Amount_EUR)
union all
(select '','',Billing_Account,'','','','Total','','',sum(Nr_Instr_Account),'',sum(Fee_Amount_EUR) ,''
from Settlement_Fees group by Billing_Account
Its is working fine
but when i am executin with select * from () its giving me error "Msg 102, Level 15, State 1, Line 33
Incorrect syntax near ')'." for the following query
SELECT *
FROM ((SELECT settlement_fees.participant_name,
settlement_fees.ACCOUNT,
settlement_fees.billing_account,
settlement_fees.descr1,
settlement_fees.market,
settlement_fees.instrum
--, IIf(Settlement_Fees.Instr_Type='Internal','bsinternal',Settlement_Fees.Instr_Type) AS Expr1
,
( CASE
WHEN settlement_fees.instr_type = 'Internal' THEN
'bsinternal'
ELSE settlement_fees.instr_type
END ),
settlement_fees.country,
settlement_fees.nr_instr_business_unit,
settlement_fees.nr_instr_account,
settlement_fees.avg_eur_rate,
settlement_fees.fee_amount_eur,
settlement_fees.value_date_adj
FROM settlement_fees)
UNION ALL
(SELECT '',
'',
billing_account,
'',
'',
'',
( CASE
WHEN instr_type LIKE '%Bridge%'
OR instr_type = '%Internal%' THEN 'Bszridge/Internal'
ELSE instr_type
END ),
'',
'',
nr_instr_account,
'',
fee_amount_eur,
''
FROM settlement_fees
GROUP BY settlement_fees.billing_account,
settlement_fees.instr_type,
settlement_fees.nr_instr_account,
fee_amount_eur)
UNION ALL
(SELECT '',
'',
billing_account,
'',
'',
'',
'Total',
'',
'',
SUM(nr_instr_account),
'',
SUM(fee_amount_eur),
''
FROM settlement_fees
GROUP BY billing_account))
You shoud name your subquery:
Select * from () subqueryName
select * from(
(SELECT Settlement_Fees.Participant_Name, Settlement_Fees.Account, Settlement_Fees.Billing_Account, Settlement_Fees.Descr1, Settlement_Fees.Market, Settlement_Fees.Instrum
--, IIf(Settlement_Fees.Instr_Type='Internal','bsinternal',Settlement_Fees.Instr_Type) AS Expr1
,(case when Settlement_Fees.Instr_Type='Internal' then 'bsinternal'
else Settlement_Fees.Instr_Type
end )
, Settlement_Fees.Country, Settlement_Fees.Nr_Instr_Business_Unit, Settlement_Fees.Nr_Instr_Account, Settlement_Fees.Avg_EUR_Rate, Settlement_Fees.Fee_Amount_EUR, Settlement_Fees.Value_Date_Adj
FROM Settlement_Fees)
union all
(select '','',Billing_Account,'','','',
( case when Instr_Type like '%Bridge%' or Instr_Type = '%Internal%' then 'Bszridge/Internal'
else Instr_Type
end )
,'','',Nr_Instr_Account ,'',Fee_Amount_EUR ,''
from Settlement_Fees group by Settlement_Fees.Billing_Account,Settlement_Fees.Instr_Type
,Settlement_Fees.Nr_Instr_Account,Fee_Amount_EUR)
union all
(select '','',Billing_Account,'','','','Total','','',sum(Nr_Instr_Account),'',sum(Fee_Amount_EUR) ,''
from Settlement_Fees group by Billing_Account
)) subqueryName
You need to give a table alias to the derived table. e.g. add as t to the very end of the query.
Additionally to fix the issue raised in the comments change
( CASE
WHEN settlement_fees.instr_type = 'Internal' THEN
'bsinternal'
ELSE settlement_fees.instr_type
END )
to
CASE
WHEN settlement_fees.instr_type = 'Internal' THEN
'bsinternal'
ELSE settlement_fees.instr_type
END AS Foo
You need to give your derived table a name. Doesn't matter what. For example:
SELECT
...
FROM
(...derived table) myDerivedTableName
You have an extra set of () and aliasing your inline view/derived table also helps e.g.
select * from(
SELECT
Settlement_Fees.Participant_Name,
Settlement_Fees.Account,
Settlement_Fees.Billing_Account,
Settlement_Fees.Descr1,
Settlement_Fees.Market,
Settlement_Fees.Instrum,
(case when Settlement_Fees.Instr_Type='Internal' then 'bsinternal'
else Settlement_Fees.Instr_Type
end ) as SomthingHere,
Settlement_Fees.Country,
Settlement_Fees.Nr_Instr_Business_Unit,
Settlement_Fees.Nr_Instr_Account,
Settlement_Fees.Avg_EUR_Rate,
Settlement_Fees.Fee_Amount_EUR,
Settlement_Fees.Value_Date_Adj
FROM Settlement_Fees
UNION ALL select
'',
'',
Billing_Account,
'',
'',
'',
( case when Instr_Type like '%Bridge%' or Instr_Type = '%Internal%' then 'Bszridge/Internal'
else Instr_Type
end ),
'',
'',
Nr_Instr_Account ,
'',
Fee_Amount_EUR ,
''
from
Settlement_Fees
group by
Settlement_Fees.Billing_Account,
Settlement_Fees.Instr_Type,
Settlement_Fees.Nr_Instr_Account,
Fee_Amount_EUR
union all select
'',
'',
Billing_Account,
'',
'',
'',
'Total',
'',
'',
sum(Nr_Instr_Account),
'',
sum(Fee_Amount_EUR) ,
''
from
Settlement_Fees
group by
Billing_Account
) as foo