Given a specific column value, merge two columns in T-SQL - sql

I have a table with the following content (simplified):
And this is the desired result:
In short, the first column has hundreds of values and sometimes repeated, for a given value of IDPRODUCTFIRST I want a RESULT column with the given value + the values ​​of IDPRODUCTSECOND.
SELECT IDPRODUCTSECOND AS RESULT
FROM [SCIOHIST].[dbo].[RELATIONPRODUCTMATCHES]
WHERE IDPRODUCTFIRST = 228697
With the query above, I can only get the values ​​from the second column, how could I add to the result column the given value (e.g. 228697) from the first column?

One method is to unpivot and select distinct values:
SELECT DISTINCT v.RESULT
FROM [SCIOHIST].[dbo].[RELATIONPRODUCTMATCHES] RPM CROSS APPLY
(VALUES (IDPRODUCTFIRST), (IDPRODUCTSECOND)) V(RESULT)
WHERE IDPRODUCTFIRST = 228697;

SELECT DISTINCT IDPRODUCTFIRST AS RESULT
FROM [SCIOHIST].[dbo].[RELATIONPRODUCTMATCHES]
--WHERE IDPRODUCTFIRST = 228697
UNION
SELECT DISTINCT IDPRODUCTSECOND AS RESULT
FROM [SCIOHIST].[dbo].[RELATIONPRODUCTMATCHES]
--WHERE IDPRODUCTFIRST = 228697
where clauses can exist or not.
IF you want duplicate value in both column are in your result you can use from "UNION ALL" instead of "UNION".

You can use Union
; With cteProd
as
(
SELECT IDPRODUCTFIRST, IDPRODUCTSECOND
FROM [SCIOHIST].[dbo].[RELATIONPRODUCTMATCHES]
)
Select RESULT from
(
SELECT IDPRODUCTFIRST, IDPRODUCTFIRST AS RESULT
FROM cteProd
Union
SELECT IDPRODUCTFIRST, IDPRODUCTSECOND AS RESULT
FROM cteProd
) Q
WHERE IDPRODUCTFIRST = 228697
Here is the fiddle

Yet another option is UNPIVOT
Example
Declare #YourTable Table ([IDPRODUCTFIRST] varchar(50),[IDPRODUCTSECOND] varchar(50)) Insert Into #YourTable Values
(228697,228699)
,(228697,228701)
Select Distinct Result
From (Select [IDPRODUCTFIRST],[IDPRODUCTSECOND]
From #YourTable
Where [IDPRODUCTFIRST] = 228697
) a
Unpivot ( Result for Item in ([IDPRODUCTFIRST],[IDPRODUCTSECOND]) ) unp
Returns
Result
228697
228699
228701

Related

Stacking my conditions in a CASE statement it's not returning all cases for each member

SELECT DISTINCT
Member_ID,
CASE
WHEN a.ASTHMA_MBR = 1 THEN 'ASTHMA'
WHEN a.COPD_MBR = 1 THEN 'COPD'
WHEN a.HYPERTENSION_MBR = 1 THEN 'HYPERTENSION'
END AS DX_FLAG
So a member may have more than one, but my statement is only returning one of them.
I'm using Teradata and trying to convert multiple columns of boolean data into one column. The statement is only returning one condition when members may have 2 or more. I tried using Select instead of Select Distinct and it made no difference.
This is a kind of UNPIVOT:
with base_data as
( -- select the columns you want to unpivot
select
member_id
,date_col
-- the aliases will be the final column value
,ASTHMA_MBR AS ASTHMA
,COPD_MBR AS COPD
,HYPERTENSION_MBR AS HYPERTENSION
from your_table
)
,unpvt as
(
select member_id, date_col, x, DX_FLAG
from base_data
-- now unpivot those columns into rows
UNPIVOT(x FOR DX_FLAG IN (ASTHMA, COPD, HYPERTENSION)
) dt
)
select member_id, DX_FLAG, date_col
from unpvt
-- only show rows where the condition is true
where x = 1

When select from insert into returns no values do something different

I want to insert rows into a table. The table is empty when I start. My query is as follows:
Select TOP 1 *
INTO #Result
FROM #SmallTable
WHERE CategoryID=11
ORDER BY ExpValue DESC;
It works flawless. But I want now to account for the case where the this returns no value. But I'm not sure how to approach this.
I could either make a case and select and ask if SELECT TOP 1 returns any values. Or I could check after I insert if there is a value present. But which approach would be better? Or is there an even better one?
You could use a union trick here to insert a dummy value should the first query not return any records:
INSERT INTO #Result (col)
SELECT TOP 1 col
FROM
(
SELECT TOP 1 col, 1 AS pos FROM #SmallTable WHERE CategoryID = 11 ORDER BY ExpValue DESC
UNION ALL
SELECT 'NA', 2
) t
ORDER BY pos;
Look at ##ROWCOUNT
This returns the number of rows affected by the last procedure.
IF ##ROWCOUNT = 0
PRINT 'Warning: No rows were inserted';
You can use apply :
select top (1) coalesce(st.CategoryID, 0) as CategoryID, . .
into #destination
from ( values (11)
) t(CategoryID) left join
#SmallTable st
on st.CategoryID = t.CategoryID
order by st.ExpValue desc;

Count of null values in all columns in total

Have 100 columns where want to find null values in all column in total.
FindNull functon helps me to convert 'null'to '1' to be able to count them
Here is my code:
(select totalAmountOfNull =
(select count(*) from (select
countOfNull=
[dmt].[findNull](column1) +
[dmt].[findNull](column2) +
[dmt].[findNull](column3) )
from dmt.tableName ) as t10 where t10.totalAmountOfNull = 3
And Answer is wrong, due to '3'. The Main problem is that I do have 100 columns in one table and want to find all null values in total. But this code gives me wrong number.
In SQL Server, you can use apply:
select count(*)
from t cross apply
(values (t.col1), (t.col2), (t.col3), . . . ) v(col)
where v.col is null;
You need to list all the columns in the values() clause.

SQL - Query column that does not exist

I have the following query where I am querying ISIN field.
SELECT Isin FROM FundPriceDetails
WHERE Isin IN
(
'ES06139009N6' , 'MAD',
'GB0002634946' , 'LSE',
'SG1L01001701' , 'SGX'
)
The second column does not exist but I wish to show it against ISIN values without inserting the row in my select query
How do I go about doing it ? A the moment I have only ISIN in my select statement. I need to create a anonymous column that contains the next column
Use a join:
SELECT x.*
FROM (SELECT 'ES06139009N6' AS lsin, 'MAD' AS col2 UNION ALL
SELECT 'GB0002634946', 'LSE' UNION ALL
SELECT 'SG1L01001701', 'SGX'
) x JOIN
FundPriceDetails fpd
ON fpd.lsin = x.lsin;

SQL Self Join to return non match records

Using SQL Self Join, I am trying to return non match records matching with where condition.
select RxNum,image from OeImage
where RxNum in ('100','200','300')
In the Table OeImage, i have values for 100,300. I don't have value for 200.
How to return not available records using self join, while Input value is passed by parameter.
If the list of non-existing values you're trying to search for is small, you can use UNION ALL like this:
SELECT *
FROM (
SELECT '100' RxNum
UNION ALL
SELECT '200'
UNION ALL
SELECT '300'
) myList
WHERE NOT EXISTS (
SELECT *
FROM OeImage
WHERE RxNum = myList.RxNum
)
If the list of elements is long or is needed in multiple queries, you can use a Temp Table variable like this:
DECLARE #myList TABLE (RxNum NVARCHAR(50))
INSERT INTO #myList
VALUES ('100')
,('200')
,('300')
SELECT *
FROM #myList
WHERE NOT EXISTS (
SELECT *
FROM OeImage
WHERE RxNum = #myList.RxNum
)