How to skip defined Combinations in sql? - join

--A=100,B=50,C=200
DECLARE #T1 TABLE (CAT1 VARCHAR(1),CAT2 VARCHAR(1),MinVal int)
INSERT INTO #T1
SELECT 'A','A',100
UNION ALL
SELECT 'A','B',50
UNION ALL
SELECT 'A','C',100
UNION ALL
SELECT 'B','A',50
UNION ALL
SELECT 'B','B',50
UNION ALL
SELECT 'B','C',50
Union all
SELECT 'C','A',100
UNION ALL
SELECT 'C','B',100
UNION ALL
SELECT 'C','C',200
select * from #T1
I have to calculate sum of MinValue
which should include only (AB,AC,BC) as whatever min of AB=BA so need to take one only.
so in result i want to get 3 rows out of 9.
Cat1|Cat2|MinVal
A|B|50
A|C|100
B|C|50
Any help will be highly appreciated.
Earlier i tried the things below but it did not work.
Select * from #T1 where Cat1<>Cat2 and ?
(what condition i need to write to avoid undesired combination.)
Here's a link

Related

Find records with ID in array of IDS and keep the order of records matching that of IDs [duplicate]

I have a simple SQL query in PostgreSQL 8.3 that grabs a bunch of comments. I provide a sorted list of values to the IN construct in the WHERE clause:
SELECT * FROM comments WHERE (comments.id IN (1,3,2,4));
This returns comments in an arbitrary order which in my happens to be ids like 1,2,3,4.
I want the resulting rows sorted like the list in the IN construct: (1,3,2,4).
How to achieve that?
You can do it quite easily with (introduced in PostgreSQL 8.2) VALUES (), ().
Syntax will be like this:
select c.*
from comments c
join (
values
(1,1),
(3,2),
(2,3),
(4,4)
) as x (id, ordering) on c.id = x.id
order by x.ordering
In Postgres 9.4 or later, this is simplest and fastest:
SELECT c.*
FROM comments c
JOIN unnest('{1,3,2,4}'::int[]) WITH ORDINALITY t(id, ord) USING (id)
ORDER BY t.ord;
WITH ORDINALITY was introduced with in Postgres 9.4.
No need for a subquery, we can use the set-returning function like a table directly. (A.k.a. "table-function".)
A string literal to hand in the array instead of an ARRAY constructor may be easier to implement with some clients.
For convenience (optionally), copy the column name we are joining to ("id" in the example), so we can join with a short USING clause to only get a single instance of the join column in the result.
Works with any input type. If your key column is of type text, provide something like '{foo,bar,baz}'::text[].
Detailed explanation:
PostgreSQL unnest() with element number
Just because it is so difficult to find and it has to be spread: in mySQL this can be done much simpler, but I don't know if it works in other SQL.
SELECT * FROM `comments`
WHERE `comments`.`id` IN ('12','5','3','17')
ORDER BY FIELD(`comments`.`id`,'12','5','3','17')
With Postgres 9.4 this can be done a bit shorter:
select c.*
from comments c
join (
select *
from unnest(array[43,47,42]) with ordinality
) as x (id, ordering) on c.id = x.id
order by x.ordering;
Or a bit more compact without a derived table:
select c.*
from comments c
join unnest(array[43,47,42]) with ordinality as x (id, ordering)
on c.id = x.id
order by x.ordering
Removing the need to manually assign/maintain a position to each value.
With Postgres 9.6 this can be done using array_position():
with x (id_list) as (
values (array[42,48,43])
)
select c.*
from comments c, x
where id = any (x.id_list)
order by array_position(x.id_list, c.id);
The CTE is used so that the list of values only needs to be specified once. If that is not important this can also be written as:
select c.*
from comments c
where id in (42,48,43)
order by array_position(array[42,48,43], c.id);
I think this way is better :
SELECT * FROM "comments" WHERE ("comments"."id" IN (1,3,2,4))
ORDER BY id=1 DESC, id=3 DESC, id=2 DESC, id=4 DESC
Another way to do it in Postgres would be to use the idx function.
SELECT *
FROM comments
ORDER BY idx(array[1,3,2,4], comments.id)
Don't forget to create the idx function first, as described here: http://wiki.postgresql.org/wiki/Array_Index
In Postgresql:
select *
from comments
where id in (1,3,2,4)
order by position(id::text in '1,3,2,4')
On researching this some more I found this solution:
SELECT * FROM "comments" WHERE ("comments"."id" IN (1,3,2,4))
ORDER BY CASE "comments"."id"
WHEN 1 THEN 1
WHEN 3 THEN 2
WHEN 2 THEN 3
WHEN 4 THEN 4
END
However this seems rather verbose and might have performance issues with large datasets.
Can anyone comment on these issues?
To do this, I think you should probably have an additional "ORDER" table which defines the mapping of IDs to order (effectively doing what your response to your own question said), which you can then use as an additional column on your select which you can then sort on.
In that way, you explicitly describe the ordering you desire in the database, where it should be.
sans SEQUENCE, works only on 8.4:
select * from comments c
join
(
select id, row_number() over() as id_sorter
from (select unnest(ARRAY[1,3,2,4]) as id) as y
) x on x.id = c.id
order by x.id_sorter
SELECT * FROM "comments" JOIN (
SELECT 1 as "id",1 as "order" UNION ALL
SELECT 3,2 UNION ALL SELECT 2,3 UNION ALL SELECT 4,4
) j ON "comments"."id" = j."id" ORDER BY j.ORDER
or if you prefer evil over good:
SELECT * FROM "comments" WHERE ("comments"."id" IN (1,3,2,4))
ORDER BY POSITION(','+"comments"."id"+',' IN ',1,3,2,4,')
And here's another solution that works and uses a constant table (http://www.postgresql.org/docs/8.3/interactive/sql-values.html):
SELECT * FROM comments AS c,
(VALUES (1,1),(3,2),(2,3),(4,4) ) AS t (ord_id,ord)
WHERE (c.id IN (1,3,2,4)) AND (c.id = t.ord_id)
ORDER BY ord
But again I'm not sure that this is performant.
I've got a bunch of answers now. Can I get some voting and comments so I know which is the winner!
Thanks All :-)
create sequence serial start 1;
select * from comments c
join (select unnest(ARRAY[1,3,2,4]) as id, nextval('serial') as id_sorter) x
on x.id = c.id
order by x.id_sorter;
drop sequence serial;
[EDIT]
unnest is not yet built-in in 8.3, but you can create one yourself(the beauty of any*):
create function unnest(anyarray) returns setof anyelement
language sql as
$$
select $1[i] from generate_series(array_lower($1,1),array_upper($1,1)) i;
$$;
that function can work in any type:
select unnest(array['John','Paul','George','Ringo']) as beatle
select unnest(array[1,3,2,4]) as id
Slight improvement over the version that uses a sequence I think:
CREATE OR REPLACE FUNCTION in_sort(anyarray, out id anyelement, out ordinal int)
LANGUAGE SQL AS
$$
SELECT $1[i], i FROM generate_series(array_lower($1,1),array_upper($1,1)) i;
$$;
SELECT
*
FROM
comments c
INNER JOIN (SELECT * FROM in_sort(ARRAY[1,3,2,4])) AS in_sort
USING (id)
ORDER BY in_sort.ordinal;
select * from comments where comments.id in
(select unnest(ids) from bbs where id=19795)
order by array_position((select ids from bbs where id=19795),comments.id)
here, [bbs] is the main table that has a field called ids,
and, ids is the array that store the comments.id .
passed in postgresql 9.6
Lets get a visual impression about what was already said. For example you have a table with some tasks:
SELECT a.id,a.status,a.description FROM minicloud_tasks as a ORDER BY random();
id | status | description
----+------------+------------------
4 | processing | work on postgres
6 | deleted | need some rest
3 | pending | garden party
5 | completed | work on html
And you want to order the list of tasks by its status.
The status is a list of string values:
(processing, pending, completed, deleted)
The trick is to give each status value an interger and order the list numerical:
SELECT a.id,a.status,a.description FROM minicloud_tasks AS a
JOIN (
VALUES ('processing', 1), ('pending', 2), ('completed', 3), ('deleted', 4)
) AS b (status, id) ON (a.status = b.status)
ORDER BY b.id ASC;
Which leads to:
id | status | description
----+------------+------------------
4 | processing | work on postgres
3 | pending | garden party
5 | completed | work on html
6 | deleted | need some rest
Credit #user80168
I agree with all other posters that say "don't do that" or "SQL isn't good at that". If you want to sort by some facet of comments then add another integer column to one of your tables to hold your sort criteria and sort by that value. eg "ORDER BY comments.sort DESC " If you want to sort these in a different order every time then... SQL won't be for you in this case.

Run 2 select statement in DB2 depending of the result of one of them

I'm trying to do an SP in DB2 with 2 select statements. If the first select returns null, perform the second one.
For example
Select a, b, c from table A where...
--If first select returns null
Select a, from table B where...
I tried a lot of ideas but none of them worked.
Thanks
You can use this general pattern, of course you will have to adapt your two result sets to match
WITH first AS
(
SELECT ..result1.. FROM table1
WHERE ..clause1..
)
SELECT ..result1.. FROM first
UNION
SELECT ..result2.. FROM table2
WHERE 0=(SELECT COUNT(1) FROM first)
AND
..clause2..
Here is a simple way to write that
Select a, from table B where...
and not exists (select * from table a where...)
union
select a,.. from table A)

Not Equal to in Inner Join

I have 3 scenarios to implement.
Case 1- When IM.Code=IME.Code and IM.Effective_st_dt=IME.effective_st_dt and IM.Effective_end_dt =IME.Effective-end_date
Action-
In this case i need to update the IM with currentMrp and currentCp.
Case 2- When IM.Code=IME.Code and IM.Effective_st_dt!=IME.effective_st_dt and IM.Effective_end_dt =IME.Effective-end_date
Action-
1.)Pick the recent Effective_st_dt record from IM and Update the Effective_end_date with (IME.Effective_st_dt)-1
2.)then Insert a new record from IME which has new effective_st_dt also this record lastMRP and lastcp is the currentmrp and Currentcp of the previous record which is updated in 1
Case 3- When IM.Code=IME.Code and IM.Effective_st_dt!=IME.effective_st_dt and IM.Effective_end_dt !=IME.Effective-end_date
Action-
1.)Pick the recent Effective_st_dt record from IM and Update the Effective_end_date with (IME.Effective_st_dt)-1
2.)then Insert a new record from IME which has new effective_st_dt also this record lastMRP and lastcp is the currentmrp and Currentcp of the previous record which is updated in 1
This is the script of my tables
Create Table IM
(
ID int idenetity (1,1)
,Code varchar(100)
,CurrentMrp float
,CurrentCP float
,lastMrp float
,lastCp float
, effective_st_dt date
,effective_end_dt date
)
Create table IME
(
Code varchar(100)
,CurrentMrp float
,CurrentCP float
,Effective_st_dt date
,Effective_end_dt date
)
insert into IM (code, currentMrp, currentCp, lastMRP, lastCP, effective_st_dt, effective_end_dt)
Select
'CA123', 10.12, 5.0, 8.20, 4, '2014-05-01', '2014-05-31'
union
Select 'CA123',15.0,5.0,10.12,8.20,'2014-06-01','2014-08-31'
union
Select 'CA121',50.0,15.0,45.0,25.0,'2014-04-01','2014-05-31'
union
Select 'CA121',75.0,25.0,50.0,15.0,'2014-06-01','2014-06-30'
union
Select 'CA131',53.0,12.0,35.0,10.0,'2014-05-01','2014-05-31'
union
Select 'CA131',60.0,15.0,53.0,12.0,'2014-06-01','2014-08-31'
Insert into IME (code,effective_st_dt,effective_end_dt)
Select ('CA123',20.0,5.0,'2014-06-01','2014-08-31')
union
Select ('CA123',25.0,6.0,'2014-06-20','2014-08-31')
union
Select ('CA123',35.0,7.0,'2014-07-15','2015-03-31')
please help me to solve this
Your help is appreciated
its better you use left join instead of inner join in this particular case, else not equal to will not give you the correct results.

Sqlite where clause with multiple values in select statement

I am trying a sqlite select query statement as below:
SELECT IndicatorText
FROM Table
where IndicatorID in('13','25','64','52','13','25','328')
AND RubricID in('1','1','1','1','1','1','6')
This gives an output but the duplicate values are not displayed. I want to display all the values of IndicatorText even though it is duplicate.
Please help me with this query.
The two IN conditions are evaluated individually.
To check both values at once, you could concatenate them so that you have a single string to compare:
SELECT IndicatorText
FROM MyTable
WHERE IndicatorID || ',' || RubricID IN (
'13,1', '25,1', '64,1', '52,1', '13,1', '25,1', '328,6')
However, doing this operation on the column values prevents the query optimizer from using indexes, so this query will be slow if the table is big.
To allow optimizations, create a temporary table with the desired values, and join that with the original table:
SELECT IndicatorText
FROM MyTable
NATURAL JOIN (SELECT 13 AS IndicatorID, 1 AS RubricID UNION ALL
SELECT 25, 1 UNION ALL
SELECT 64, 1 UNION ALL
SELECT 52, 1 UNION ALL
SELECT 13, 1 UNION ALL
SELECT 25, 1 UNION ALL
SELECT 328, 6)

Extracting data from two tables

I have two tables "CAR" -it's fields are- (car_id,name), the second table "CARSFORSALE" contains cars for sale (id,car_id,....)
How i can get 10 rows from "CARSFORSALE" table for each car_id in one query
that mean if i have 7 car_id my result will be <=70
select 1,car_id
union all
select 2,car_id
union all
select 3,car_id
union all
select 4,car_id
union all
select 5,car_id
union all
select 6,car_id
union all
select 7,car_id
union all
select 8,car_id
union all
select 9,car_id
union all
select 10,car_id

Resources