Pivot not give expected result - sql

I m using pivot and unpivot but I dot get expected output
Here is my sample data set
Table 1
id c_code
-----------------
123 1
456 1
Table 2
id c_code i_t_code i_code
----------------------
123 1 TWinc 10
123 1 TBinc 20
123 1 TSinc 30
Table 3
i_code i_t_code i_name
------------------------------
10 TWinc abc
20 TBinc xyz
30 TSinc pqr
Here is my query
Query
select * from (
select id,inc,i_t_code from (
select a.id,b.i_name,cast(b.i_code AS
VARCHAR(128)) as i_code,b.i_t_code
from
table_1 a
join
table_2 b
on a.id= b.id
and
a.c_code = b.c_code
join
tabl_3 c on c.i_code = b.i_code
and
c.i_t_code = b.i_t_code
on a.i_code = b.i_code
) d
Unpivot
(
inc for details in (i_name,i_code)
) as unpt) as uppt_res
PIVOT
(
max(inc)
FOR [i_t_code] IN ([TWinc],[TBinc],[TSinc])
) AS P
Expected output:
id TWinc_n TWinc_c TBinc_n TBinc_c TSinc_n TSinc_c
------------------------------------------------------------
123 abc 10 xyz 20 pqr 30
Actual output:
id TWinc TBinc TSinc
------------------------------------
123 abc xyz pqr
How can do this ??
It is possible using pivot or any other solution is there
can anyone help to fix this ?

You're going to have to give your data some variation if you want to stop pivot from compressing equal data items together when it's converting row data into column names and picking the max(inc) - probably easiest to do by changing the contents of the unpivoted data, tacking on a row number:
SELECT * FROM
(
select stoneid, inc, CONCAT(inclusion_type_id, ROW_NUMBER()OVER(PARTITION BY inclusion_type_id ORDER BY inc)) as inclusion_type_id FROM
(
select
a.stoneid,
b.inclusion_name,
cast(b.inclusion_code AS VARCHAR(128)) as inclusion_code,
b.inclusion_type_id,
b.inclusion_type_code
from
PACKET.STONE_LAB_INCLUSIONS a
inner join
MASTER.INCLUSION_MASTER b
on
a.inclusion_code = b.inclusion_code and
a.inclusion_type_code = b.inclusion_type_code
inner join
packet.stone_details c
on
c.stoneid = a.stoneid and
c.certificate_code = a.certificate_code
) d
UNPIVOT(inc for details in (inclusion_name,inclusion_code)) as unpt
) uppt_res
PIVOT
(
MAX(inc)
FOR [inclusion_type_id] IN ([TWinc1],[TWinc2],[TBinc1],[TBinc2],[TSinc1],[TSinc2])
) AS P
If you're desperate to have column names the same, you can alias the results of this query rather than select *

Related

How to identify non-existing keys with reference to a table that has all mandatory keys, SQL?

I have the table 'Table01' which contains the keys that should be mandatory:
id
1
2
3
4
And I also have the table 'Table02' which contains the records to be filtered:
id
customer
weight
1
a
100
2
a
300
3
a
200
4
a
45
1
b
20
2
b
100
3
b
17
1
c
80
4
c
90
2
d
30
3
d
30
4
d
50
So I want to identify which are the mandatory id's that the table 'Table02' does not have, and in turn identify which is the 'customer' of each id's that the table 'Table02' does not have.
The resulting table should look like this:
customer
id
b
4
c
2
c
3
d
1
What I have tried so far is a 'rigth join'.
proc sql;
create table table03 as
select
b.id
from table02 a
right join table01 b
on a.id=b.id
where a.id is null;
run;
But that query is not identifying all the id's that should be mandatory.
I hope someone can help me, thank you very much.
here is one way:
select cl.customerid , a.id
from
Table1 a
cross join
( select customerid
from table2
group by customerid
) cl
where not exists ( select 1 from table2 b
where b.customerid = cl.customerid
and b.id = a.id
)
You can use an EXCEPT between two sub-selects. The first creates a matrix of all possibilities, and the except table is a selection of the extant customers.
Example:
data ids;
do id = 1 to 4; output; end;
run;
data have;
input id customer $ weight;
datalines;
1 a 100
2 a 300
3 a 200
4 a 45
1 b 20
2 b 100
3 b 17
1 c 80
4 c 90
2 d 30
3 d 30
4 d 50
run;
proc sql;
create table want(label='Customers missing some ids') as
select matrix.*
from
(select distinct have.customer, ids.id from have, ids) as matrix
except
(select customer, id from have)
;
quit;
If you are doing it in SQL server. Something like #eshirvana above posted, but also you can use with cte:
;with cte as
(
SELECT t1.id, t2.Customer
FROM Table01 t1
cross join (select distinct customer from Table02)
)
SELECT a.customer, a.id FROM cte a
LEFT JOIN Table02 b
ON a.id=b.id AND a.customer=b.customer
where b.id is null

SQL JOIN: Return rows from LEFT and RIGHT table when there is a match

I have a #tmp table, and I need to find all records from the LEFT table and from the RIGHT table that have a matching Name and Coverage.
-- select * from #tmp
--#tmp table
ID Name IsConverted Coverage EarliestPolicyEffectiveDate
1 abc 1 Test1 9/1/2017
2 abc 0 Test1 9/2/2017
3 abc 0 Auto 9/3/2017
4 xyz 0 Home 9/3/2017
-- select * from #tmp where IsConverted = 0
--LEFT TABLE
ID Name IsConverted Coverage
2 abc 0 Test1
3 abc 0 Auto
4 xyz 0 Home
-- select * from #tmp where IsConverted = 1
--RIGHT TABLE
ID Name IsConverted Coverage
1 abc 1 Test1
-- DESIRED RESULTS
ID Name IsConverted Coverage
1 abc 1 Test1
2 abc 0 Test1
-- CURRENT RESULTS
ID Name IsConverted Coverage
2 abc 0 Test1
select *
from
(SELECT * FROM #tmp tmp WHERE tmp.IsConverted = 0) nc
join
(SELECT * FROM #tmp tmp WHERE tmp.IsConverted = 1) ic on ic.Name = nc.Name and ic.Coverage = nc.Coverage
I need to be able to get the matching records from both tables, left and right. The reason for this is very complicated and does not add any additional information for this post.
I have tried FULL OUTER JOIN, CROSS APPLY, OUTER APPLY. Nothing is working.
EDIT:
Preferably I would like to use JOIN because once I find the matching results, I still need access to the left table and the right table because I need to make sure the LEFT.EarliestPolicyEffectiveDate within 15 days of RIGHT.EarliestPolicyEffectiveDate .
I'm not sure I can do that if I do UNION ALL.
Like below example:
select *
from
(SELECT * FROM #tmp tmp WHERE tmp.IsConverted = 0) nc
join
(SELECT * FROM #tmp tmp WHERE tmp.IsConverted = 1) ic on ic.Name = nc.Name and ic.Coverage = nc.Coverage
where
nc.EarliestPolicyEffectiveDate between DATEADD(d, -15, ic.EarliestPolicyEffectiveDate) and DATEADD(d, 15, ic.EarliestPolicyEffectiveDate)
I think there are better ways to do this, but UNION ALL and EXISTS seems to work here:
SELECT *
FROM #tmp t
WHERE IsConverted = 1
AND EXISTS(SELECT 1 FROM #tmp
WHERE IsConverted = 0
AND Name = t.Name
AND Coverage = t.Coverage)
UNION ALL
SELECT *
FROM #tmp t
WHERE IsConverted = 0
AND EXISTS(SELECT 1 FROM #tmp
WHERE IsConverted = 1
AND Name = t.Name
AND Coverage = t.Coverage);
This works for me. have a subquery to get all the matching names between LEFT and RIGHT. and a subquery to get all matching coverage between LEFT AND RIGHT. then use 'AND' to link them together in the WHERE clause
select * from #tmp
where name in (Select LEF.Name from LEF
INNER JOIN RIG ON LEF.NAME = RIG.NAME)
and coverage in (Select LEF.coverage from LEF
INNER JOIN RIG ON LEF.coverage = RIG.coverage)
result:
ID NAME IsConverted Coverage EarliestPolicyEffectiveDate
----------- ---------- ----------- ---------- ---------------------------
1 abc 1 Test1 2017-09-01
2 abc 0 Test1 2017-09-02
I think I see now that you are trying to join the LEFT TABLE directly to the RIGHT TABLE, not using #tmp as a middle join.
You need to UNION the two where they intersect.
Psuedocode:
SELECT * FROM LEFT TABLE WHERE EXISTS(matching row in RIGHT TABLE)
UNION
SELECT * FROM RIGHT TABLE WHERE EXISTS(matching row in LEFT TABLE)

Simply by the Query

Table name is group. Column name is groupno,name,grouprefno,detail,undergroupno
Sample data of group
groupno name grouprefno detail undergroupno
1 A 001 abc 0
2 B 002 cde 0
3 AA 001001 abc 1
4 AC 001002 abc 1
5 AAA 001001001 DDD 3
6 DDD 001001002 ddd 3
7 www 001002001 223 4
8 eee 001002002 222 4
Now i want to get rows which name's are AA, AC and which are comes under the AA,AC
So i tried like this
select no from group where substring(grouprefno,1,
(select length(grouprefno) from group where name ='AA'
))=(select grouprefno from group
where name ='AA' ) union all select no from group where substring(grouprefno,1,
(select length(grouprefno) from group where name ='AC'
))=(select grouprefno from group
where groupname ='AC' )
Its Work Fine, But i want another solution because it has 2 sub query's in side of single query. It has any other feasible solution?
Am using postgresql 9.1
Try:
WITH q AS(
SELECT *
FROM Table1
WHERE name IN ('AA','AC')
)
SELECT * FROM q
UNION ALL
SELECT * FROM Table1 t
WHERE t.undergroupno IN (
SELECT groupno FROM q
)
Demo: http://sqlfiddle.com/#!12/fce65/3

Using table joins to put seq no to the grouped items in the select SQL Query result

can any one help to solve this issue in SQL SERVER 2008. I want to put seq numbering to the grouped items in the select query result.
select a.grade, a.name, a.age, seqno
from tab A join tab B on A.id = B.id
[group based on Grade column]
The result should show as shown below.
SeqNo Grade Name Age
----- ----- ---- ---
1 A abc 23
2 A xyz 7
1 B dfg 34
2 B sxd 23
3 B vvv 56
In the below query, how i can join the second table and using a "join'
SELECT ROW_NUMBER() OVER ( PARTITION BY [a.Grade] ORDER BY [a.Name]) AS 'SeqNo',
[a.Grade], [a.Name], [a.Age]
FROM Employee a WITH (NOLOCK)
ORDER BY [a.Grade],[a.Name]

Get the max value of a column from set of rows

I have a table like this
Table A:
Id Count
1 4
1 16
1 8
2 10
2 15
3 18
etc
Table B:
1 sample1.file
2 sample2.file
3 sample3.file
TABLE C:
Count fileNumber
16 1234
4 2345
15 3456
18 4567
and so on...
What I want is this
1 sample1.file 1234
2 sample2.file 3456
3 sample3.file 4567
To get the max value from table A I used
Select MAX (Count) from A where Id='1'
This works well but my problem is when combining data with another table.
When I join Table B and Table A, I need to get the MAX for all Ids and in my query I dont know what Id is.
This is my query
SELECT B.*,C.*
JOIN A on A.Id = B.ID
JOIN C on A.id = B.ID
WHERE (SELECT MAX(COUNT)
FROM A
WHERE Id = <what goes here????>)
To summarise, what I want is Values from Table B, FileNumber from Table c (where the count is Max for ID from table A).
UPDATE: COrrecting table C above. Looks like I need Table A.
I think this is the query you're looking for:
select b.*, c.filenumber from b
join (
select id, max(count) as count from a
group by id
) as NewA on b.id = NewA.id
join c on NewA.count = c.count
However, you should take into account that I don't get why for id=1 in tableA you choose the 16 to match against table C (which is the max) and for id=2 in tableA you choose the 10 to match against table C (which is the min). I assumed you meant the max in both cases.
Edit:
I see you've updated tableA data. The query results in this, given the previous data:
+----+---------------+------------+
| ID | FILENAME | FILENUMBER |
+----+---------------+------------+
| 1 | sample1.file | 1234 |
| 2 | sample2.file | 3456 |
| 3 | sample3.file | 4567 |
+----+---------------+------------+
Here is a working example
Using Mosty’s working example (renaming the keyword count to cnt for a column name), this is another approach:
with abc as (
select
a.id,
a.cnt,
rank() over (
partition by a.id
order by cnt desc
) as rk,
b.filename
from a join b on a.id = b.id
)
select
abc.id, abc.filename, c.filenumber
from abc join c
on c.cnt = abc.cnt
where rk = 1;
select
PreMax.ID,
B.FileName,
C2.FileNumber
from
( select C.id, max( C.count ) maxPerID
from TableC C
group by C.ID
order by C.ID ) PreMax
JOIN TableC C2
on PreMax.ID = C2.ID
AND PreMax.maxPerID = C2.Count
JOIN TableB B
on PreMax.ID = B.ID