How to select row based on existance of value in other column - sql

I realise the title to this question may be vague but I am not sure how to phrase it. I have the following table:
i_id option p_id
---- ------ ----
1 A 4
1 B 8
1 C 6
2 B 3
2 C 5
3 A 7
3 B 3
4 E 11
How do I select a row based on the value of the option column for each unique i_id: if 'C' exists, select the row, else select row with 'B' else with 'A' so that result set is:
i_id option p_id
---- ------ ----
1 C 6
2 C 5
3 B 3

select i_id, option, p_id
from (
select
i_id,
option,
p_id,
row_number() over (partition by i_id order by case option when 'C' then 0 when 'B' then 1 when 'A' then 2 end) takeme
from thetable
where option in ('A', 'B', 'C')
) foo
where takeme = 1

This will give you the values ordered by C, B, A, while removing any i_id record that does not have one of these values.
WITH ranked AS
(
SELECT i_id, [option], p_id
, ROW_NUMBER() OVER (PARTITION BY i_id ORDER BY CASE [option]
WHEN 'C' THEN 1
WHEN 'B' THEN 2
WHEN 'A' THEN 3
ELSE 4
END) AS rowNumber
FROM yourTable
WHERE [option] IN ('A', 'B', 'C')
)
SELECT r.i_id, r.[option], r.p_id
FROM ranked AS r
WHERE r.rowNumber = 1

create table t2 (
id int,
options varchar(1),
pid int
)
insert into t2 values(1, 'A', 4)
insert into t2 values(1, 'B', 8)
insert into t2 values(1, 'C', 6)
insert into t2 values(1, 'E', 7)
select t2.* from t2,
(select id, MAX(options) as op from t2
where options <> 'E'
group by id) t
where t2.id = t.id and t2.options = t.op

Well, I would suggest that this problem can be made easier if you can assign a numeric "score" to each letter, such that "better" letters have higher scores. Then you can use MAX to find, for each group, the row with the highest "score" for the option. Since 'A' < 'B' < 'C', we could cheat here and use option as the score, and thus:
SELECT t1.i_id, t1.option, t1.p_id
FROM thetable t1
INNER JOIN (SELECT t2.i_id, MAX(option)
FROM thetable t2
GROUP BY t2.i_id) AS maximums
ON t1.i_id = maximums.i_id
WHERE option != 'D'
This assumes that {i_id, option} is a natural key of the table (i.e., that no two rows will have the same combination of values for those two columns; or, alternatively, that you have an uniqueness constraint on that pair of columns).

Related

update row same as row above if condition meet with number

i have data like this
id type
1. a
2. b
3. c
4. c
5. d
6. c
7. c
target
id type. group
1. a. 1
2. b. 2
3. c. 2
4. c. 2
5. d. 3
6. c. 3
7. c. 3
if type c, group value take value from above row.
i can goal this with loop condition and update but that take to much time because looping update many row
how can i achiev this with single update statement with sql server 2008
This should work
declare #t table (id int primary key, val char(1));
insert into #t values
(1, 'a')
, (2, 'b')
, (3, 'c')
, (4, 'c')
, (5, 'd')
, (6, 'c')
, (7, 'c');
select *
, sum(case when val = 'c' then 0 else 1 end) over (order by id) as grp
from #t t
order by id;
id val grp
----------- ---- -----------
1 a 1
2 b 2
3 c 2
4 c 2
5 d 3
6 c 3
7 c 3
Follow the link below for a running demo.
Demo
I am posting this as an alternative to the answer given by #palarazzi which may already be sufficient. This answer is robust to type letters occurring in any amount.
WITH cte AS (
SELECT t1.id AS id1, t1.type AS type1, t2.id AS id2, t2.type AS type2
FROM yourTable t1
INNER JOIN yourTable t2
ON (t1.id = t2.id AND t1.type <> 'c') OR
(t1.id > t2.id AND t1.type = 'c' AND t2.type <> 'c')
),
cte2 AS (
SELECT id1, type2,
ROW_NUMBER() OVER (PARTITION BY id1 ORDER BY id2 DESC) rn
FROM cte
)
SELECT
id1 AS id, type2 AS type,
DENSE_RANK() OVER (ORDER BY type2) [group]
FROM cte2
WHERE rn = 1;
Demo

ORACLE get rows with condition value equals something but not equals to anything else

I have rows that look like .
OrderNo OrderStatus SomeOtherColumn
A 1
A 1
A 3
B 1 X
B 1 Y
C 2
C 3
D 2
I want to return all orders that have only one possible value of orderstatus. For e.g Here order B has only order status 1 SO result should be
B 1 X
B 1 Y
Notes:
Rows can be duplicated with same order status. For e.g. B here.
I am interested in the order having a very peculiar status for e.g. 1 here and not having any other status. So if B had a status of 3 at any point of time it is disqualified.
You can use not exists:
select t.*
from t
where not exists (select 1
from t t2
where t.orderno = t2.orderno and t.OrderStatus = t2.OrderStatus
);
If you just want the orders where this is true, you can use group by and having:
select orderno
from t
group by orderno
having min(OrderStatus) = max(OrderStatus);
If you only want a status of 1 then add max(OrderStatus) = 1 to the having clause.
Here is one way to do it. It does not handle the case where the status can be NULL; if that is possible, you will need to explain how you want it handled.
SQL> create table test_data ( orderno, status, othercol ) as (
2 select 'A', 1, null from dual union all
3 select 'A', 1, null from dual union all
4 select 'A', 3, null from dual union all
5 select 'B', 1, 'X' from dual union all
6 select 'B', 1, 'Y' from dual union all
7 select 'C', 2, null from dual union all
8 select 'C', 3, null from dual union all
9 select 'D', 2, null from dual
10 );
Table created.
SQL> variable input_status number
SQL> exec :input_status := 1
PL/SQL procedure successfully completed.
SQL> column orderno format a8
SQL> column othercol format a8
SQL> select orderno, status, othercol
2 from (
3 select t.*, count(distinct status) over (partition by orderno) as cnt
4 from test_data t
5 )
6 where status = :input_status
7 and cnt = 1
8 ;
ORDERNO STATUS OTHERCOL
-------- ---------- --------
B 1 X
B 1 Y
One way to handle NULL status (if that may happen), if in that case the orderno should be rejected (not included in the output), is to define the cnt differently:
count(case when status != :input_status or status is null then 1 end)
over (partition by orderno) as cnt
and in the outer query change the WHERE clause to a single condition,
where cnt = 0
Count distinct OrderStatus partitioned by OrderNo and show only rows where number equals one:
select OrderNo, OrderStatus, SomeOtherColumn
from ( select t.*, count(distinct orderstatus) over (partition by orderno) cnt
from t )
where cnt = 1
SQLFiddle demo
Just wanted to add something to Gordon's answer, using a stats function:
select orderno
from t
group by orderno
having variance(orderstatus) = 0;

SQL Query with group by clause, but counting two distinct values as if they were the same

I have a simple table with two columns, like the one below:
Id | Name
0 | A
1 | A
2 | B
3 | B
4 | C
5 | D
6 | E
7 | E
I want to make a SQL query which will count how many times each "Name" appears on the table. However, I need a few of these values to count as if they were the same. For example, a normal group by query would be:
select Name, count(*)
from table
group by Name
The above query would produce the result:
Name | Count
A | 2
B | 2
C | 1
D | 1
E | 2
but I need the query to count "A" and "B" as if they were only "A", and to count "D" and "E" as if they were only "D", so that the result would be like:
Name | Count
A | 4 // (2 "A"s + 2 "B"s)
C | 1
D | 3 // (1 "D" + 2 "E"s)
How can I make this kind of query?
You can make translation with case. Also, you can use subquery or CTE so you don't have to repeat yourself:
with cte as (
select
case Name
when 'B' then 'A'
when 'E' then 'D'
else Name
end as Name
from table
)
select Name, count(*)
from cte
group by Name
or with with online translation table:
select
isnull(R.B, t.Name), count(*)
from table as t
left outer join (
select 'A', 'B' union all
select 'E', 'D'
) as R(A, B) on R.A = t.Name
group by isnull(R.B, t.Name)
If you need A and B, D and E, to count the same, you can build a query like this:
SELECT
CASE Name WHEN 'B' THEN 'A' WHEN 'E' THEN 'D' ELSE Name END as Name
, COUNT(*)
FROM table
GROUP BY CASE Name WHEN 'B' THEN 'A' WHEN 'E' THEN 'D' ELSE Name END
Demo on sqlfiddle.
With a layer of abstraction and a CASE (SQL Fiddle example):
;WITH x AS
(
SELECT CASE Name WHEN 'B' THEN 'A'
WHEN 'E' THEN 'D'
ELSE Name
END AS Name
FROM Table1
)
SELECT Name, COUNT(1)
FROM x
GROUP BY Name
With a translation table (SQL Fiddle):
CREATE TABLE Translate(FromName char(1), ToName char(1));
INSERT INTO Translate VALUES ('B', 'A'), ('E', 'D');
SELECT COALESCE(t.ToName, a.Name) Name, COUNT(1)
FROM Table1 a
LEFT OUTER JOIN Translate t ON a.Name = t.FromName
GROUP BY COALESCE(t.ToName, a.Name)
FWIW, you can also do this with a VALUES derived table instead of a real table (SQL Fiddle):
SELECT COALESCE(t.ToName, a.Name) Name, COUNT(1)
FROM Table1 a
LEFT OUTER JOIN
(
VALUES ('B', 'A'),
('E', 'D')
) t(FromName, ToName) ON a.Name = t.FromName
GROUP BY COALESCE(t.ToName, a.Name)
this works
select t.a,count(t.id) from (
select case name when 'A' then 'A' when 'B' then 'A'
when 'C' then 'C' when 'D' then 'C'
when 'D' then 'D' when 'E' then 'D' end as A,id
from test) as t
group by A;

Filter unique records from a database while removing double not-null values

This is kind of hard to explain in words but here is an example of what I am trying to do in SQL. I have a query which returns the following records:
ID Z
--- ---
1 A
1 <null>
2 B
2 E
3 D
4 <null>
4 F
5 <null>
I need to filter this query so that each unique record (based on ID) appears only once in the output and if there are multiple records for the same ID, the output should contain the record with the value of Z column being non-null. If there is only a single record for a given ID and it has value of null for column Z the output still should return that record. So the output from the above query should look like this:
ID Z
--- ---
1 A
2 B
2 E
3 D
4 F
5 <null>
How would you do this in SQL?
You can use GROUP BY for that:
SELECT
ID, MAX(Z) -- Could be MIN(Z)
FROM MyTable
GROUP BY ID
Aggregate functions ignore NULLs, returning them only when all values on the group are NULL.
If you need to return both 2-B and 2-E rows:
SELECT *
FROM YourTable t1
WHERE Z IS NOT NULL
OR NOT EXISTS
(SELECT * FROM YourTable t2
WHERE T2.ID = T1.id AND T2.z IS NOT NULL)
SELECT ID
,Z
FROM YourTable
WHERE Z IS NOT NULL
DECLARE #T TABLE ( ID INT, Z CHAR(1) )
INSERT INTO #T
( ID, Z )
VALUES ( 1, 'A' ),
( 1, NULL )
, ( 2, 'B' ) ,
( 2, 'E' ),
( 3, 'D' ) ,
( 4, NULL ),
( 4, 'F' ),
( 5, NULL )
SELECT *
FROM #T
; WITH c AS (SELECT ID, r=COUNT(*) FROM #T GROUP BY ID)
SELECT t.ID, Z
FROM #T t JOIN c ON t.ID = c.ID
WHERE c.r =1
UNION ALL
SELECT t.ID, Z
FROM #T t JOIN c ON t.ID = c.ID
WHERE c.r >=2
AND z IS NOT NULL
This example assumes you want two rows returned for ID = 2.
with tmp (id, cnt_val) as
(select id,
sum(case when z is not null then 1 else 0 end)
from t
group by id)
select t.id, t.z
from t
inner join tmp on t.id = tmp.id
where tmp.cnt_val > 0 and t.z is not null
or tmp.cnt_val = 0 and t.z is null
WITH CTE
AS (
SELECT id
,z
,ROW_NUMBER() OVER (
PARTITION BY id ORDER BY coalesce(z, '') DESC
) rn
FROM #T
)
SELECT id
,z
FROM CTE
WHERE rn = 1

SQL to check for all values in column

I have the following table in Oracle DB.
ID VALUE
-----------
1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3
4 1
How can I select ID's which have all 3 values (1,2,3)
The simplest option is generally something like this
SQL> ed
Wrote file afiedt.buf
1 with x as (
2 select 1 id, 1 val from dual union all
3 select 1 id, 2 val from dual union all
4 select 1 id, 3 val from dual union all
5 select 2 id, 1 val from dual union all
6 select 2 id, 2 val from dual union all
7 select 3 id, 1 val from dual union all
8 select 3 id, 2 val from dual union all
9 select 3 id, 3 val from dual union all
10 select 4 id, 1 val from dual
11 )
12 select id
13 from x
14 where val in (1,2,3)
15 group by id
16* having count(distinct val) = 3
SQL> /
ID
----------
1
3
The WHERE clause identifies the values you're interested in. The HAVING clause tells you how many of those values need to exist. If you wanted all the rows that had at least 2 of the 3 values, for example, you'd change the HAVING clause to look for a COUNT of 2.
If a particular val is guaranteed to occur at most once per id, you can eliminate the distinct in the HAVING clause.
Try this:
SELECT ID
FROM TABLENAME T
WHERE EXISTS (SELECT *
FROM TABLENAME T1
WHERE T1.ID = T.ID AND T1.VALUE = '1')
AND EXISTS (SELECT *
FROM TABLENAME T2
WHERE T1.ID = T.ID AND T2.VALUE = '2')
AND EXISTS (SELECT *
FROM TABLENAME T3
WHERE T1.ID = T.ID AND T2.VALUE = '3')
or
SELECT ID
FROM TABLENAME T
WHERE (SELECT COUNT( * )
FROM (SELECT VALUE
FROM TABLENAME T1
WHERE T1.ID = T.ID
GROUP BY VALUE)) = 3;
where 3 is number of values which can be calculated by a
SELECT COUNT( * )
FROM TABLENAME T1
GROUP BY VALUE
so this will be general purpose:
SELECT ID
FROM TABLENAME T
WHERE (SELECT COUNT( * )
FROM (SELECT VALUE
FROM TABLENAME T1
WHERE T1.ID = T.ID
GROUP BY VALUE)) = (SELECT COUNT( * )
FROM TABLENAME T2
GROUP BY VALUE)
Here's an option... each expression in the HAVING clause is counting the number of values that are found equal to 1, 2, or 3. If any of these counts is less than 1, then the ID will not be returned.
http://sqlfiddle.com/#!4/00fdc/8
SELECT ID
FROM myTable
GROUP BY ID
HAVING
SUM(DECODE(VALUE, 1, 1, 0)) > 0 AND
SUM(DECODE(VALUE, 2, 1, 0)) > 0 AND
SUM(DECODE(VALUE, 3, 1, 0)) > 0
EDIT - To require value 1, and either 2 or 3:
SELECT ID
FROM myTable
GROUP BY ID
HAVING
SUM(DECODE(VALUE, 1, 1, 0)) > 0 AND
(
SUM(DECODE(VALUE, 2, 1, 0)) > 0 OR
SUM(DECODE(VALUE, 3, 1, 0)) > 0
)
select id from (select id,sum(case when value=1 then 1 else 0 end) as 'v1',
sum(case when value=2 then 1 else 0 end) as 'v2',
sum(case when value=3 then 1 else 0 end) as 'v3'
from orac group by id) as final
where v1>0 and v2>0 and v3>0
With this option you will get more than the IDs, up to your application to select the column you want:
SELECT ID,
sum(CASE WHEN VALUE = 1 THEN 1 ELSE 0 END) AS ONE,
sum(CASE WHEN VALUE = 2 THEN 1 ELSE 0 END) AS TWO,
sum(CASE WHEN VALUE = 3 THEN 1 ELSE 0 END) AS THREE
FROM MYTABLE
GROUP BY ID
HAVING ONE >= 1 AND TWO >= 1 AND THREE >= 1;
alternatively if your case is specific (only values 1, 2, 3 are possible, and no duplicate values are allowed), then you could try the following one:
SELECT ID,
count(VALUE) AS VALUECOUNT
FROM MYTABLE
GROUP BY ID
HAVING VALUECOUNT = 3;
I would take care before going that way, as you might get side effects if later you want to add additional values. But it's still worth proposing if your current case fits the restrictions given above.
And, of course, if you don't like the idea of fetching these intermediate counts, enclose the queries I gave within another select
SELECT ID FROM (
...
)