I have table like
Tabel data
+-------+-------+
| name1 | name2 |
+-------+-------+
| AA | XX |
| BB | YY |
| CC | ZZ |
+-------+-------+
and I want the output like
Edit
+-------+
| name1 |
+-------+
| AA |
| XX |
| BB |
| YY |
| CC |
| ZZ |
+-------+
can u please guide me to query to obtain this task
You can use UNION ALL or UNION . UNION will create a DISTINCT result Set. If you don't want, you can use UNION ALL, which will simply concat the data
SELECT NAME1 as NAME FROM YOUR_TABLE
UNION
SELECT NAME2 FROM YOUR_TABLE
ORDER BY NAME
EDIT: For your updated requirements
with my_data(name1,name2) as
(
select 'AA','XX' from dual
union
select 'BB','YY' from dual
union
select 'CC','ZZ' from dual
),
indexed_my_data(name1,name2,row_sequence) as
(
select name1,name2, row_number() over (order by null) from my_data
)
select name1,row_sequence,'A' as col_sequence from indexed_my_data
union all
select name2,row_sequence,'B' from indexed_my_data
ORDER BY row_sequence,col_sequence;
Related
I have a table as below
I want output like below
This means I have few predefined pairs, example
if one employee is coming from both HR_INTERNAL and HR_EXTERNAL, take only that record which is from HR_INTERNAL
if one employee is coming from both SALES_INTERNAL and SALES_EXTERNAL, take only that record which is from SALES_INTERNAL
etc.
Is there a way to achieve this?
I used ROW_NUMBER to rank
ROW_NUMBER() OVER(PARTITION BY "EMPID" ORDER BY SOURCESYSTEM ASC) AS RANK_GID
I just put them on a table like this:
create or replace table predefined_pairs ( pairs ARRAY );
insert into predefined_pairs select [ 'HR_INTERNAL', 'HR_EXTERNAL' ] ;
insert into predefined_pairs select [ 'SALES_INTERNAL', 'SALES_EXTERNAL' ] ;
Then I use the following query to produce the output you wanted:
select s.sourcesystem, s.empid,
CASE WHEN COUNT(1) OVER(PARTITION BY EMPID) = 1 THEN 'ValidRecord'
WHEN p.pairs[0] IS NULL THEN 'ValidRecord'
WHEN p.pairs[0] = s.sourcesystem THEN 'ValidRecord'
ELSE 'InvalidRecord'
END RecordValidity
from source s
left join predefined_pairs p on array_contains( s.sourcesystem::VARIANT, p.pairs ) ;
+-------------------+--------+----------------+
| SOURCESYSTEM | EMPID | RECORDVALIDITY |
+-------------------+--------+----------------+
| HR_INTERNAL | EMP001 | ValidRecord |
| HR_EXTERNAL | EMP001 | InvalidRecord |
| SALES_INTERNAL | EMP002 | ValidRecord |
| SALES_EXTERNAL | EMP002 | InvalidRecord |
| HR_EXTERNAL | EMP004 | ValidRecord |
| SALES_INTERNAL | EMP005 | ValidRecord |
| PURCHASE_INTERNAL | EMP003 | ValidRecord |
+-------------------+--------+----------------+
Let's say I have a table with many columns like col1, col2, col3, id, variantId, col4, col5 etc
However I am only interested in id, variantId which look like this:
+----------+-----------+
| id | variantId |
+----------+-----------+
| a | 11 |
| a | 12 |
| b | 31 |
| c | 41 |
| c | 54 |
| d | abc |
| e | xyz |
| e | xyz |
+----------+-----------+
I need distinct ids which having count of distinct variantId more than once
In this case I would only get a and c
You can use group by and having:
select id
from t
group by id
having min(variant_id) <> max(variant_id);
You can also use:
having count(distinct variant_id) > 1
Try with group by having clause
select id
from table
group by id
having count(distinct variant_id) > 1
You can do it more efficiently with EXISTS:
select distinct t.id
from tablename t
where exists (
select 1 from tablename
where id = t.id and variantid <> t.variantid
)
Problem: I am querying a poorly normalized database (I have no say in the design of the data and cannot change it)
Given the following database:
------------------------------------------
| Name | Codes |
------------------------------------------
| Josh | A2A-8292 |
-------------------------------------------
| Adam | D2C-1292, B2A-7292 |
-------------------------------------------
| Jery | A2A-1292, F2A-2292, |
| | C2A-2292 |
-------------------------------------------
How can I write a query that returns the normalized version e.g:
------------------------------------------
| Name | Codes |
------------------------------------------
| Josh | A2A-8292 |
-------------------------------------------
| Adam | D2C-1292 |
-------------------------------------------
| Adam | B2A-7292 |
-------------------------------------------
| Jery | A2A-1292 |
-------------------------------------------
| Jery | F2A-2292 |
-------------------------------------------
| Jery | C2A-2292 |
-------------------------------------------
If you can't use a TVF, here's another option
Example
Select A.Name
,B.*
From YourTable A
Cross Apply (
Select RetSeq = row_number() over (order by (Select null))
,RetVal = ltrim(rtrim(B2.i.value('(./text())[1]', 'varchar(max)')))
From (Select x = Cast('<x>' + replace(Codes,',','</x><x>')+'</x>' as xml).query('.')) as B1
Cross Apply x.nodes('x') AS B2(i)
) B
Returns
Name RetSeq RetVal
Josh 1 A2A-8292
Adam 1 D2C-1292
Adam 2 B2A-7292
Jery 1 A2A-1292
Jery 2 F2A-2292
Jery 3 C2A-2292
Taking string split function from this answer: T-SQL split string
You could run your query as following:
SELECT T.Name, X.*
FROM TABLE AS T
CROSS APPLY dbo.splitstring(Codes) AS X;
I'm having a serious problem with one of my import tables. I've imported an Excel file to a SQL Server table. The table ImportExcelFile now looks like this (simplified):
+----------+-------------------+-----------+------------+--------+--------+-----+---------+
| ImportId | Excelfile | SheetName | Field1 | Field2 | Field3 | ... | Field10 |
+----------+-------------------+-----------+------------+--------+--------+-----+---------+
| 1 | C:\Temp\Test.xlsx | Sheet1 | Age / Year | 2010 | 2011 | | 2018 |
| 2 | C:\Temp\Test.xlsx | Sheet1 | 0 | Value1 | Value2 | | Value9 |
| 3 | C:\Temp\Test.xlsx | Sheet1 | 1 | Value1 | Value2 | | Value9 |
| 4 | C:\Temp\Test.xlsx | Sheet1 | 2 | Value1 | Value2 | | Value9 |
| 5 | C:\Temp\Test.xlsx | Sheet1 | 3 | Value1 | Value2 | | Value9 |
| 6 | C:\Temp\Test.xlsx | Sheet1 | 4 | Value1 | Value2 | | Value9 |
| 7 | C:\Temp\Test.xlsx | Sheet1 | 5 | NULL | NULL | | NULL |
+----------+-------------------+-----------+------------+--------+--------+-----+---------+
I now want to insert those values from Field1 to Field10 to the table AgeYear(in my original table there are about 70 columns and 120 rows). The first row (Age / Year, 2010, 2011, ...) is the header row. The column Field1 is the leading column. I want to save the values in the following format:
+-----------+-----+------+--------+
| SheetName | Age | Year | Value |
+-----------+-----+------+--------+
| Sheet1 | 0 | 2010 | Value1 |
| Sheet1 | 0 | 2011 | Value2 |
| ... | ... | ... | ... |
| Sheet1 | 0 | 2018 | Value9 |
| Sheet1 | 1 | 2010 | Value1 |
| Sheet1 | 1 | 2011 | Value2 |
| ... | ... | ... | ... |
| Sheet1 | 1 | 2018 | Value9 |
| ... | ... | ... | ... |
+-----------+-----+------+--------+
I've tried the following query:
DECLARE #sql NVARCHAR(MAX) =
';WITH cte AS
(
SELECT i.SheetName,
ROW_NUMBER() OVER(PARTITION BY i.SheetName ORDER BY i.SheetName) AS rn,
' + #columns + ' -- #columns = 'Field1, Field2, Field3, Field4, ...'
FROM dbo.ImportExcelFile i
WHERE i.Sheetname LIKE ''Sheet1''
)
SELECT SheetName,
age Age,
y.[Year]
FROM cte
CROSS APPLY
(
SELECT Field1 age
FROM dbo.ImportExcelFile
WHERE SheetName LIKE ''Sheet1''
AND ISNUMERIC(Field1) = 1
) a (age)
UNPIVOT
(
[Year] FOR [Years] IN (' + #columns + ')
) y
WHERE rn = 1'
EXEC (#sql)
So far I'm getting the desired ages and years. My problem is that I don't know how I could get the values. With UNPIVOT I don't get the NULL values. Instead it fills the whole table with the same values even if they are NULL in the source table.
Could you please help me?
Perhaps an alternative approach. This is not dynamic, but with the help of a CROSS APPLY and a JOIN...
The drawback is that you'll have to define the 70 fields.
Example
;with cte0 as (
Select A.ImportId
,A.SheetName
,Age = A.Field1
,B.*
From ImportExcelFile A
Cross Apply ( values ('Field2',Field2)
,('Field3',Field3)
,('Field10',Field10)
) B (Item,Value)
)
,cte1 as ( Select * from cte0 where ImportId=1 )
Select A.SheetName
,[Age] = try_convert(int,A.Age)
,[Year] = try_convert(int,B.Value)
,[Value] = A.Value
From cte0 A
Join cte1 B on A.Item=B.Item
Where A.ImportId>1
Returns
Current OutPut:
PM_DIG_OUTPUT_1_CLOSED
PM_DIG_OUTPUT_10_CLOSED
PM_DIG_OUTPUT_14_CLOSED
PM_DIG_OUTPUT_15_CLOSED
PM_DIG_OUTPUT_16_CLOSED
PM_DIG_OUTPUT_2_CLOSED
PM_DIG_OUTPUT_3_CLOSED
Expected Output:
PM_DIG_OUTPUT_1_CLOSED
PM_DIG_OUTPUT_2_CLOSED
PM_DIG_OUTPUT_3_CLOSED
PM_DIG_OUTPUT_10_CLOSED
PM_DIG_OUTPUT_14_CLOSED
PM_DIG_OUTPUT_15_CLOSED
PM_DIG_OUTPUT_16_CLOSED
Index of Number is not fixed
What is the best way to achieve this order?
EDIT:
Some records also contain following data
PRM_CODE_MIO_DIGITALOUT_WRITE_LOGIC_CARD2_DO1
PRM_CODE_MIO_DIGITALOUT_WRITE_LOGIC_CARD2_DO2
PRM_CODE_MIO_DIGITALOUT_WRITE_LOGIC_CARD2_DO3
PRM_CODE_MIO_DIGITALOUT_WRITE_LOGIC_CARD2_DO4
Query:
SQLFIDDLEExample
SELECT *
FROM Table1 t1
ORDER BY CAST(REPLACE(REPLACE(col, 'PM_DIG_OUTPUT_', ''),'_CLOSED', '') AS int)
Result:
| COL |
|-------------------------|
| PM_DIG_OUTPUT_1_CLOSED |
| PM_DIG_OUTPUT_2_CLOSED |
| PM_DIG_OUTPUT_3_CLOSED |
| PM_DIG_OUTPUT_10_CLOSED |
| PM_DIG_OUTPUT_14_CLOSED |
| PM_DIG_OUTPUT_15_CLOSED |
| PM_DIG_OUTPUT_16_CLOSED |
EDITED ANSWER
You could use query:
SQLFIDDLEExample
SELECT *
FROM Table1 t1
ORDER BY CASE WHEN LEFT(col, 2) = 'PM'
THEN CAST(REPLACE(REPLACE(col, 'PM_DIG_OUTPUT_', ''),'_CLOSED', '') AS int)
ELSE RIGHT(col,1) END
Result:
| COL |
|-----------------------------------------------|
| PM_DIG_OUTPUT_1_CLOSED |
| PRM_CODE_MIO_DIGITALOUT_WRITE_LOGIC_CARD2_DO1 |
| PRM_CODE_MIO_DIGITALOUT_WRITE_LOGIC_CARD2_DO2 |
| PM_DIG_OUTPUT_2_CLOSED |
| PM_DIG_OUTPUT_3_CLOSED |
| PRM_CODE_MIO_DIGITALOUT_WRITE_LOGIC_CARD2_DO3 |
| PRM_CODE_MIO_DIGITALOUT_WRITE_LOGIC_CARD2_DO4 |
| PM_DIG_OUTPUT_10_CLOSED |
| PM_DIG_OUTPUT_14_CLOSED |
| PM_DIG_OUTPUT_15_CLOSED |
| PM_DIG_OUTPUT_16_CLOSED |
Assuming that after the number there's only one underscore and some text (then no matter what is before the number, if it's at least one underscore and some text).
Edit for new values. It will sort by the numbers if it can find them and won't break if no numbers were found by matching the pattern:
select
*,
substring(y,len(y)-charindex('_',reverse(y))+2,100) as num
from (
select
*,
substring(x,1,len(x)-charindex('_',reverse(x))) as y
from (
select 'PM_DIG_OUTPUT_1_CLOSED' as x union all
select 'PM_DIG_OUTPUT_10_CLOSED' union all
select 'PM_DIG_OUTPUT_14_CLOSED' union all
select 'PM_DIG_OUTPUT_15_CLOSED' union all
select 'PM_DIG_OUTPUT_16_CLOSED' union all
select 'PM_DIG_OUTPUT_2_CLOSED' union all
select 'PM_DIG_OUTPUT_3_CLOSED' union all
select 'PRM_CODE_MIO_DIGITALOUT_WRITE_LOGIC_CARD2_DO1' union all
select 'PRM_CODE_MIO_DIGITALOUT_WRITE_LOGIC_CARD2_DO2' union all
select 'PRM_CODE_MIO_DIGITALOUT_WRITE_LOGIC_CARD2_DO3' union all
select 'PRM_CODE_MIO_DIGITALOUT_WRITE_LOGIC_CARD2_DO4'
) x
) y
order by
case when isnumeric(substring(y,len(y)-charindex('_',reverse(y))+2,100))=1 then cast(substring(y,len(y)-charindex('_',reverse(y))+2,100) as int) end