I have 2 script as following:
First one:
SELECT [Fm].[Id], [Sdp].[FirstName], [Sdp].[LastName], [Sdp].[SSN],
[Sdp].[StoreName], [Sdp].[PostalCode], [Fc].[Id], [Sdp].[Address]
FROM [SRM].[SiteMembers].[DProfile] AS [Sdp]
INNER JOIN [SRM].[SiteMembers].[Member] AS [Sm]
ON [Sdp].[Member_Id] = [Sm].[Id]
INNER JOIN [FRM].[Members].[Member] AS [Fm]
ON [Sm].[UserId] = [Fm].[UserId]
INNER JOIN [SRM].[General].[City] AS [Sc]
ON [Sdp].[City_Id]=[Sc].[Id]
INNER JOIN [FRM].[General].[City] AS [Fc]
ON [Fc].[Title]=[Sc].[Title]
COLLATE SQL_Latin1_General_CP1_CI_AS
WHERE ISNUMERIC([Sdp].[PostalCode])=1;
And Second one:
SELECT [Fm].[Id], [Sdp].[FirstName], [Sdp].[LastName], [Sdp].[SSN],
[Sdp].[StoreName], 0, [Fc].[Id], [Sdp].[Address]
FROM [SRM].[SiteMembers].[DProfile] AS [Sdp]
INNER JOIN [SRM].[SiteMembers].[Member] AS [Sm]
ON [Sdp].[Member_Id] = [Sm].[Id]
INNER JOIN [FRM].[Members].[Member] AS [Fm]
ON [Sm].[UserId] = [Fm].[UserId]
INNER JOIN [SRM].[General].[City] AS [Sc]
ON [Sdp].[City_Id]=[Sc].[Id]
INNER JOIN [FRM].[General].[City] AS [Fc]
ON [Fc].[Title]=[Sc].[Title]
COLLATE SQL_Latin1_General_CP1_CI_AS
WHERE ISNUMERIC([Sdp].[PostalCode])=0;
The difference between this 2 script is that the first one select columns with numeric postal code and second one select 0 for the non numeric postal code so how can I merge this 2 script together in one script, I am not talking about Union, I am interesting to use some condition in select query for non numeric postal code select 0. Does any one have any idea?
I would skip the where statement and create one column for the Numeric postal code and one for the other one. Like this:
SELECT
[Fm].[Id],
[Sdp].[FirstName],
[Sdp].[LastName],
[Sdp].[SSN],
[Sdp].[StoreName],
(
CASE WHEN ISNUMERIC([Sdp].[PostalCode])=1
THEN 0
ELSE NULL
END
) AS NumericPostalCode,
(
CASE WHEN ISNUMERIC([Sdp].[PostalCode])=0
THEN [Sdp].[PostalCode]
ELSE NULL
END
) AS PostalCode,
[Fc].[Id],
[Sdp].[Address]
FROM
[SRM].[SiteMembers].[DProfile] AS [Sdp]
INNER JOIN [SRM].[SiteMembers].[Member] AS [Sm]
ON [Sdp].[Member_Id] = [Sm].[Id]
INNER JOIN [FRM].[Members].[Member] AS [Fm]
ON [Sm].[UserId] = [Fm].[UserId]
INNER JOIN [SRM].[General].[City] AS [Sc]
ON [Sdp].[City_Id]=[Sc].[Id]
INNER JOIN [FRM].[General].[City] AS [Fc]
ON [Fc].[Title]=[Sc].[Title]
COLLATE SQL_Latin1_General_CP1_CI_ASĀ“
Edit 1
I know that this will result in two columns. But you can not have to data types in one column. But I think that you can do it something like this as well.
SELECT
[Fm].[Id],
[Sdp].[FirstName],
[Sdp].[LastName],
[Sdp].[SSN],
[Sdp].[StoreName],
(
CASE WHEN ISNUMERIC([Sdp].[PostalCode])=0
THEN [Sdp].[PostalCode]
ELSE '0'
END
) AS PostalCode,
[Fc].[Id],
[Sdp].[Address]
This will work becuase the numeric one are '0' as a varchar.
Edit 2
You can also do it like this:
SELECT CAST('asdasd' AS sql_variant)
UNION ALL
SELECT CAST(0 AS sql_variant)
But this is a dirty solution for this problem. The sql_variant is a database object. So my conclusion is: Use to column if you what to have different data types. If the values can be the same data type use the same column. Do not use sql_variant to solve problems like this. You will pay a high price in maintaining the code.
Hope this help.
Use a case statement in the selected column list and remove the where clause:
SELECT [Fm].[Id], [Sdp].[FirstName], [Sdp].[LastName], [Sdp].[SSN],
[Sdp].[StoreName],
case when isnumeric([Sdp].[PostalCode]) = 1 then [Sdp].[PostalCode] else 0 end,
[Fc].[Id], [Sdp].[Address]
FROM [SRM].[SiteMembers].[DProfile] AS [Sdp]
INNER JOIN [SRM].[SiteMembers].[Member] AS [Sm]
ON [Sdp].[Member_Id] = [Sm].[Id]
INNER JOIN [FRM].[Members].[Member] AS [Fm]
ON [Sm].[UserId] = [Fm].[UserId]
INNER JOIN [SRM].[General].[City] AS [Sc]
ON [Sdp].[City_Id]=[Sc].[Id]
INNER JOIN [FRM].[General].[City] AS [Fc]
ON [Fc].[Title]=[Sc].[Title]
COLLATE SQL_Latin1_General_CP1_CI_AS
Related
I have the following query which allows me to join the TransactionClass tables base on TransactionClassID from either the primary table (Transactions) or TransactionRules based on a condition as below:
SELECT
Description,
TC.Name,
(CASE
WHEN (TR.TransactionRuleId > 0)
THEN TR.TransactionRuleId
ELSE T.TransactionClassId
END) As ClassId
FROM Transactions AS T
LEFT JOIN TransactionRules TR ON T.Description LIKE TR.Pattern
LEFT JOIN TransactionClasses TC ON TC.TransactionClassId =
(CASE
WHEN (TR.TransactionRuleId > 0)
THEN TR.TransactionClassId
ELSE T.TransactionClassId
END)
The query is running on SQL Server,
In effect, it retrieves the correct TransactionClass entry depending on whether or not the join on TransactionRules was successful or not.
The above query works, but I am trying to simplify the query so that I do not have to repeat the CASE expression in two places.
I attempted to capture the result of the case expression in a variable and use that as follows:
SELECT
Description,
x
FROM Transactions AS T
LEFT JOIN TransactionRules TR
ON T.Description LIKE TR.Pattern
LEFT JOIN TransactionClasses TC
ON TC.TransactionClassId = x
WHERE x = (CASE
WHEN (TR.TransactionRuleId > 0)
THEN TR.TransactionRuleId
ELSE T.TransactionClassId
END)
But I get the error:
[S0001][207] Line 8: Invalid column name 'x'.
Where am I going wrong in my attempt to have only one CASE Expression?
CROSS APPLY is a tidy way to reuse a calculated value e.g.
SELECT
[Description]
, TC.[Name]
, Class.Id
FROM Transactions AS T
LEFT JOIN TransactionRules TR ON T.[Description] LIKE TR.Pattern
CROSS APPLY (
VALUES (
CASE
WHEN TR.TransactionRuleId > 0
THEN TR.TransactionRuleId
ELSE T.TransactionClassId
END
)
) AS Class (Id)
LEFT JOIN TransactionClasses TC ON TC.TransactionClassId = Class.Id;
I am trying to get the HTS "harmonized code" from two different tables.
STKMP purchased, STKMM Manufactured.
When I run my query, there are items that are missing the HTS from STKMP, I would like to replace NULLS
with the data on STKMM. I have tried case when but it gives me no results.
Select distinct
ltrim(rtrim(boldh.FEBOL#)) as BOL,
--ltrim(rtrim(bolh.FESCS#)) as ShipTo,
--ltrim(rtrim(bolh.FESNME)) as CustomerName,
--ltrim(rtrim(bolh.FGCPO#)) as CustPO,
--ltrim(rtrim(ocri.DDCSPI)) as CustLine,
ltrim(rtrim(bold.FGCPT#)) as CustPart,
ltrim(rtrim(bolh.FESNME)) as CustName,
ltrim(rtrim(bolh.FESAD1)) as CustStreet,
ltrim(rtrim(bolh.FESAD2)) as CustStreet1,
ltrim(rtrim(bolh.FESAD3)) as CustCityState,
ltrim(rtrim(stkmp.AWHARM)) as HTS,
case when STKMP.AWHARM is null then STKMM.AVHARM else stkmp.AWHARM end as HTTT,
ltrim(rtrim(V6CORG)) as COO,
ltrim(rtrim(awdes1)) as Descrip
--ltrim(rtrim([FGQSHO])) as QTY
FROM BOLH
left join bold on bolh.FEBOL# = bold.FGBOL#
left join ocri on bold.FGORD# = ocri.DDORD# and bold.FGITEM = ocri.DDITM#
left join STKA on ocri.DDPART = stka.v6part
left join STKMP on stka.V6PART = STKMP.AWPART
left join STKMM on STKMP.AWPART = STKMM.AVPART
Thanks
COALESCE ( expression [ ,...n ] )
Reference: https://learn.microsoft.com/en-us/sql/t-sql/language-elements/coalesce-transact-sql?view=sql-server-ver15
COALESCE(STKMP.AWHARM, stkmp.AWHARM) AS HTTT
Alternatively, to see if you got some issues with your joins and/or both values are null you could take it one step further, like this.
COALESCE(STKMP.AWHARM, stkmp.AWHARM, 'Both values are NULL') AS HTTT
Also, there are few more other options are there.
By using ISNULL
SELECT ISNULL(STKMP.AWHARM, stkmp.AWHARM) AS HTTT
By Using IIF Statement
SELECT IIF(STKMP.AWHARM IS NOT NULL,STKMP.AWHARM,stkmp.AWHARM) AS HTTT
I have set of two queries. In first query, if is separate from second, I got good results.
First query
SELECT *
FROM
(
SELECT nks.[Id]
, nks.[IdNarudzbe]
, nks.[IdArtikla] as artikal
, nks.[IdUsluge]
, nks.[Naziv]
, nks.Kolicina
, p.Naziv as kupac
, p.Id as kupacId
, p.Adresa
, p.Telefon
, nkz.[BrojDokumenta] AS nalog
, nkz.[BrojDokumentaKroz] AS nalogKroz
, nkz.[RokIsporuke]
, nkz.[IdNastaloOdDokumenta]
, d.Naziv as drzava
FROM [dbo].[NarudzbaKupacaStavke] nks
LEFT JOIN [dbo].[NarudzbeKupacaZaglavlje] nkz
ON nkz.Id = nks.IdNarudzbe
LEFT JOIN dbo.Partneri p
ON nkz.IdKupac = p.Id
LEFT JOIN dbo.Drzave d
ON p.IdDrzava = d.Id
WHERE idArtikla IN ('FP80PUR-08', 'FP80PUR-09', 'FP80PUR-12')
AND nkz.[VrstaDokumenta] = 'PRO'
AND nkz.StatusArhive = 0
--...
from first query nkz.[IdNastaloOdDokumenta] is important to second
SELECT BrojDokumenta
, BrojDokumentaKroz
FROM .[dbo].[NarudzbeKupacaZaglavlje]
where id = nkz.[IdNastaloOdDokumenta]
For ex. In first query I got nkz.[IdNastaloOdDokumenta] = 20. Number 20 I use in second query in where statement, and value I get from BrojDokumenta, I would like to join to first query.
I was wondering if is possible to make one query out of these two. I think I can not union operator because number of column from these two queries don't match.
The same table, and the same columns are already in the first query. Perhaps you want a self-join, like this:
FROM [dbo].[NarudzbaKupacaStavke] nks
LEFT JOIN [dbo].[NarudzbeKupacaZaglavlje] nkz
ON nkz.Id = nks.IdNarudzbe
LEFT JOIN [dbo].[NarudzbeKupacaZaglavlje] nkz2
ON nkz2.Id = nkz.[IdNastaloOdDokumenta]
LEFT JOIN dbo.Partneri p
ON nkz.IdKupac = p.Id
LEFT JOIN dbo.Drzave d
ON p.IdDrzava = d.Id
WHERE idArtikla IN ('FP80PUR-08', 'FP80PUR-09', 'FP80PUR-12')
AND nkz.[VrstaDokumenta] = 'PRO'
AND nkz.StatusArhive = 0
I am learning SQL case statements and have the following stored procedure.
Select PT.[ID] 'TransactionID', PT.BatchNumber, PT.SequenceNumber, PT.TransactionDate,
PT.TerminalID, PT.TotalAmount, PT.TransactionTypeID, TT.TransactionType,
PT.PAN 'EmbossLine',PT.PreBalanceAmount, PT.PostBalanceAmount, RefTxnID, SettlementDate,PaidCash, CreditAmount, DiscountAmount,
RefPAN, Remarks, PT.Product,
case PT.Product when 1 then 'Taxi' end 'ProductName'
case PT.Product when 2 then 'Airport Lounge' end 'ProductName'
into #Temp
from POS_Transactions PT inner join TransactionType TT on TT.TransactionTypeID = PT.TransactionTypeID
where
PT.[ID] not in (Select distinct isnull(TransactionID,0) from Testcards)
and (PT.TransactionDate >= #DateFrom)
and (PT.TransactionDate < #DateTo)
and (PT.TransactionTypeID = #TransactionTypeID or #TransactionTypeID = -999)
select T.*, C.EmbossLine+' ' as 'EmbossLine', C.EmbossLine as 'EmbossLine1',
C.EmbossName, PM.MerchantID, PM.MerchantName1, C.AccountNumber, C.VehicleNumber
from #Temp T
inner join Card C on C.EmbossLine= T.EmbossLine
inner join Terminal on Terminal.TerminalID = T.TerminalID
inner join Merchant PM on PM.MerchantID = Terminal.MerchantID
where C.Status <>'E3'
and C.CardID not in (Select distinct isnull(CardID,0) from Testcards)
and (PM.MerchantID =#MerchantID or #MerchantID='-999')
and (C.EmbossLine like '%'+#EmbossLine+'%' or #EmbossLine like '-999')
and (C.EmbossName like '%'+#EmbossName+'%' or #EmbossName like '-999')
order by T.TransactionDate, MerchantName1, T.BatchNumber, T.SequenceNumber
drop table #Temp
When I create it, command is executed succesfully. However when I call it, it throws following error
Column names in each table must be unique. Column name 'ProductName'
in table '#Temp' is specified more than once.
I think I have problem in the syntax in these lines
case PT.Product when 1 then 'Taxi' end 'ProductName'
case PT.Product when 2 then 'Airport Lounge' end 'ProductName'
Can someone identify?
Your line is indeed a problem.
I suspect you're after something like:
case PT.Product
when 1 then 'Taxi'
when 2 then 'Airport Lounge'
end 'ProductName'
In your syntax you make two different cases, resulting in two columns being selected, both called the same.
Above the case can return two different values into the one row.
Not being a SQL expert, and also only being semi-competent in CTE, how can I code this statement use the resultset from the following subquery within the main query, as our SQL Server is 2000.
declare #subcategoryConcatenate varchar(3999)
set #subcategoryConcatenate = ''
select #subcategoryConcatenate = #subcategoryConcatenate + pumpCategoryName + ',' FROM
(SELECT
SCD.PUMPCATEGORYNAME,
SCD.ENGINECATEGORYNAME,
SCD.DETAILEDDESCRIPTION
FROM PRTTICKHDR PHDR
INNER JOIN BIDHDR BHDR ON PHDR.DELIV_TICKET_NUMBER = BHDR.DTICKET
INNER JOIN PRTTICKITEM PITM ON PHDR.CONNECTION_ID = PITM.CONNECTION_ID AND PHDR.DELIV_TICKET_NUMBER = PITM.DELIV_TICKET_NUMBER
LEFT JOIN SUBCATEGORYDESCRIPTION SCD ON PITM.ITEM = SCD.PUMPCATEGORY
WHERE SCD.pumpCategoryName IS NOT NULL)
subcategoryDescription
select #subcategoryConcatenate
SELECT
PHDR.CONNECTION_ID AS CONNECTION_ID,
BHDR.OFFICE AS OFFICE,
CMP.NAME AS DEPOT,
CMP.ADDR1 AS DEPOT_ADDR1,
CMP.ADDR2 AS DEPOT_ADDR2,
CMP.CITY AS DEPOT_CITY,
CMP.STATE AS DEPOT_STATE,
CMP.ZIP AS DEPOT_ZIP,
CMP.PHONENUM AS DEPOT_PHONE,
CMP.FAXNUM AS DEPOT_FAX,
ACT.NAME AS ACTIVITY,
SAL.SALES_PERSON_NAME AS SALESPERSON,
BHDR.DTICKET AS DELIV_TICKET_NUMBER,
BHDR.PO_NUMBER,
BHDR.CREATED AS CREATED_DATE,
BHDR.DDATE AS ESTIMATED_START_DATE,
BHDR.PROJ_STOP_DATE AS PROJECTED_STOP_DATE,
CUR.ID,
CUR.CODE,
CUR.EXCHANGE_RATE,
CST.TERMS,
BHDR.ORDBY AS ORDERED_BY,
PHDR.ORDERED_BY_CONTACT,
BHDR.ACCT AS ACCOUNT,
BHDR.NAME AS CUSTOMER,
BHDR.ADDR1 AS CUST_ADDR1,
BHDR.ADDR2 AS CUST_ADDR2,
BHDR.CITY AS CUST_CITY,
BHDR.STATE AS CUST_STATE,
BHDR.ZIP AS CUST_ZIP,
PHDR.SHIP_TO_NAME,
PHDR.SHIP_TO_ADDR1,
PHDR.SHIP_TO_ADDR2,
PHDR.SHIP_TO_CITY,
PHDR.SHIP_TO_STATE,
PHDR.SHIP_TO_ZIP,
PITM.PRINT_SEQUENCE,
PITM.ITEM,
PITM.SUBGROUP,
PITM.DESCRIPTION,
SCD.PUMPCATEGORYNAME,
SCD.ENGINECATEGORYNAME,
SCD.DETAILEDDESCRIPTION,
PITM.QUANTITY,
PITM.UNIT_OF_MEASURE,
PITM.BILLING_LOGIC_TYPE,
PITM.INVENTORY_TYPE,
PITM.CHARGEABLE_DAYS,
PITM.MINIMUM_CHARGE,
PITM.WEEKLY_CHARGE,
PITM.MONTHLY_CHARGE,
PITM.UNINVOICED_NET,
PITM.UNINVOICED_VAT
FROM PRTTICKHDR PHDR
INNER JOIN BIDHDR BHDR ON PHDR.DELIV_TICKET_NUMBER = BHDR.DTICKET
INNER JOIN PRTTICKITEM PITM ON PHDR.CONNECTION_ID = PITM.CONNECTION_ID AND PHDR.DELIV_TICKET_NUMBER = PITM.DELIV_TICKET_NUMBER
INNER JOIN COMPANY CMP ON BHDR.OFFICE = CMP.OFFICE
LEFT JOIN SUBCATEGORYDESCRIPTION SCD ON PITM.ITEM = SCD.PUMPCATEGORY
INNER JOIN ACTIVITIES ACT ON BHDR.ACTIVITY_ID = ACT.ID
INNER JOIN SALES_PERSON SAL ON BHDR.SALES_PERSON = SAL.SALES_PERSON
INNER JOIN CUSTOMERS CST ON BHDR.ACCT = CST.CUSTNUM
INNER JOIN CURRENCY CUR ON CST.CURRENCY_ID = CUR.ID
ORDER BY
BHDR.DTICKET,
PITM.PRINT_SEQUENCE
ASC
SQL Server 2000 doesn't support CTEs. Your options are to either make a view out of the subquery if it's used a lot, or to do an inline view:
select
.. stuff..
from
table1 t1
join table2 t2 on ...stuff...
join (
select
...
from
...
where
...
) inline on ... stuff ...
where
....
You need a user-defined function.
From the looks of it, each PRTTICKITEM can have more than one PUMPCATEGORY?
(The question needs to better explain the desired results.)
In that case, your UDF would look something like this:
CREATE FUNCTION GetPumpCategoriesByItem (#ItemID int)
RETURNS varchar (8000)
AS
BEGIN
DECLARE
#CategoryList varchar (8000)
SET #CategoryList = NULL -- MUST be null to avoid leading comma.
SELECT
#CategoryList = COALESCE (#CategoryList + ', ', '') + SCD.PUMPCATEGORYNAME
FROM
SUBCATEGORYDESCRIPTION SCD
WHERE
SCD.PUMPCATEGORY = #ItemID
ORDER BY
SCD.PUMPCATEGORYNAME
RETURN #CategoryList
END
.
To use it would be something like this:
SELECT
PITM.ITEM,
dbo.GetPumpCategoriesByItem (PITM.ITEM),
... ...
FROM
... ...
INNER JOIN PRTTICKITEM PITM ON ... ...
... ...