Select DISTINCT from two columns in t-SQL - sql

Say, if I have the following table:
CREATE TABLE tbl (ID INT, Type UNIQUEIDENTIFIER)
INSERT tbl VALUES
(1, N'D9D09D5B-AF63-484C-8229-9762B52972D0'),
(2, N'D9D09D5B-AF63-484C-8229-9762B52972D6'),
(3, N'D9D09D5B-AF63-484C-8229-9762B52972D9'),
(3, N'D9D09D5B-AF63-484C-8229-9762B52972D2'),
(4, N'D9D09D5B-AF63-484C-8229-9762B52972D0')
and I need to select distinct ID columns but also whatever the Type column value that is associated with it. If I do the following:
select distinct id, type from tbl
It returns the whole table when I need only this:
1, N'D9D09D5B-AF63-484C-8229-9762B52972D0'
2, N'D9D09D5B-AF63-484C-8229-9762B52972D6'
3, N'D9D09D5B-AF63-484C-8229-9762B52972D9'
4, N'D9D09D5B-AF63-484C-8229-9762B52972D0'
I know it must be something simple, but what am I missing here?

As per you comment you need to want to select first type in the list. So you can achieve this by using subquery like this:
SELECT id, (SELECT TOP 1 type FROM tbl a WHERE id = b.id)
FROM tbl b GROUP BY id
See this SQLFiddle

select id, min(type) from tbl group by id

Related

Insert/join table on multiple conditions

I’ve a table that looks like this:
Table A
Version,id
5060586,22285
5074515,22701
5074515,22285
7242751,22701
7242751,22285
I want to generate a new key called groupId that is inserted as my example below:
Table A
Version,id,groupId
5060586,22285,1
5074515,22701,2
5074515,22285,2
7242751,22701,2
7242751,22285,2
I want the groupId to be the same as long as the id's are the same in the different versions. So for example version 5074515 and 7242751 has the same id's so therefor the groupId will be the same. If all the id's aren't the same a new groupId should be added as it has in version 5060586.
How can i solve this specific problem in SQL oracle?
One approach is to create a unique value representing the set of ids in each version, then assign a groupid to the unique values of that, then join back to the original data.
INSERT ALL
INTO t (version,id) VALUES (5060586,22285)
INTO t (version,id) VALUES (5074515,22701)
INTO t (version,id) VALUES (5074515,22285)
INTO t (version,id) VALUES (7242751,22701)
INTO t (version,id) VALUES (7242751,22285)
SELECT 1 FROM dual;
WITH groups
AS
(
SELECT version
, LISTAGG(id,',') WITHIN GROUP (ORDER BY id) AS group_text
FROM t
GROUP BY version
),
groupids
AS
(
SELECT group_text, ROW_NUMBER() OVER (ORDER BY group_text) AS groupid
FROM groups
GROUP BY group_text
)
SELECT t.*, groupids.groupid
FROM t
INNER JOIN groups ON t.version = groups.version
INNER JOIN groupids ON groups.group_text = groupids.group_text;
dbfiddle.uk
You can use:
UPDATE tableA t
SET group_id = ( SELECT COUNT(DISTINCT id)
FROM TableA x
WHERE x.Version <= t.version );
Which, for the sample data:
CREATE TABLE TableA (
Version NUMBER,
id NUMBER,
group_id NUMBER
);
INSERT INTO TableA (Version, id)
SELECT 5060586,22285 FROM DUAL UNION ALL
SELECT 5074515,22701 FROM DUAL UNION ALL
SELECT 5074515,22285 FROM DUAL UNION ALL
SELECT 7242751,22701 FROM DUAL UNION ALL
SELECT 7242751,22285 FROM DUAL;
Then, after the update:
SELECT * FROM tablea;
Outputs:
VERSION
ID
GROUP_ID
5060586
22285
1
5074515
22701
2
5074515
22285
2
7242751
22701
2
7242751
22285
2
db<>fiddle here

PostgreSQL: How to insert multiple values without multiple selects?

I have the problem that I need to insert into a table with 2 entries, where one value is constant but fetched from another table, and the other one is the actual content that changes.
Currently I have something like
INSERT INTO table (id, content) VALUES
((SELECT id FROM customers WHERE name = 'Smith'), 1),
((SELECT id FROM customers WHERE name = 'Smith'), 2),
((SELECT id FROM customers WHERE name = 'Smith'), 5),
...
As this is super ugly, how can I do the above in Postgres without the constant SELECT repetition?
Yet another solution:
insert into table (id, content)
select id, unnest(array[1, 2, 5]) from customers where name = 'Smith';
You can cross join the result of the select with your values:
INSERT INTO table (id, content)
select c.id, d.nr
from (
select id
from customers
where name = 'Smith'
) as c
cross join (values (1), (2), (5) ) as d (nr);
This assumes that the name is unique (but so does your original solution).
Well, I believe you can do something like this:
DECLARE
id customers.id%TYPE;
BEGIN
select c.id into id FROM customers c WHERE name = 'Smith';
INSERT INTO table (id, content) VALUES
(id, 1),
(id, 2),
....
END;

Creating tables on-the-fly

It is often convenient in PosgreSQL to create "tables" on the fly so to refer to them, e.g.
with
selected_ids as (
select 1 as id
)
select *
from someTable
where id = (select id from selected_ids)
Is it impossible to provide multiple values as id this way? I found this answer that suggests using values for similar problem, but I have problem with translating it to the example below.
I would like to write subqueries such as
select 1 as id
union
select 2 as id
union
select 7 as id
or
select 1 as id, 'dog' as animal
union
select 7 as id, 'cat' as animal
in more condensed way, without repeating myself.
You can use arguments in the query alias:
with selected_ids(id) as (
values (1), (3), (5)
)
select *
from someTable
where id = any (select id from selected_ids)
You can also use join instead of a subquery, example:
create table some_table (id int, str text);
insert into some_table values
(1, 'alfa'),
(2, 'beta'),
(3, 'gamma');
with selected_ids(id) as (
values (1), (2)
)
select *
from some_table
join selected_ids
using(id);
id | str
----+------
1 | alfa
2 | beta
(2 rows)
You can pass id and animal field in WITH like this
with selected_ids(id,animal) as (
values (1,'dog'), (2,'cat'), (3,'elephant'),(4,'rat')--,..,.. etc
)
select *
from someTable
where id = any (select id from selected_ids)
You should use union and IN statement like this:
with
selected_ids as (
select 1 as id
union
select 2 as id
union
select 3 as id
....
)
select *
from someTable
where id in (select id from selected_ids)
after reviewing wingedpanther's idea and looking for it, you can use his idea IF those id's are continuously like this:
with
selected_ids as (
SELECT * FROM generate_series(Start,End) --(1,10) for example
)
select *
from someTable
where id in (select id from selected_ids)
If they are not continuously , the only way you can do that is by storing those ID's in a different table(maybe you have it already and if not insert it)
And then:
select *
from someTable
where id in (select id from OtherTable)

Counting the rows of a column where the value of a different column is 1

I am using a select count distinct to count the number of records in a column. However, I only want to count the records where the value of a different column is 1.
So my table looks a bit like this:
Name------Type
abc---------1
def----------2
ghi----------2
jkl-----------1
mno--------1
and I want the query only to count abc, jkl and mno and thus return '3'.
I wasn't able to do this with the CASE function, because this only seems to work with conditions in the same column.
EDIT: Sorry, I should have added, I want to make a query that counts both types.
So the result should look more like:
1---3
2---2
SELECT COUNT(*)
FROM dbo.[table name]
WHERE [type] = 1;
If you want to return the counts by type:
SELECT [type], COUNT(*)
FROM dbo.[table name]
GROUP BY [type]
ORDER BY [type];
You should avoid using keywords like type as column names - you can avoid a lot of square brackets if you use a more specific, non-reserved word.
I think you'll want (assuming that you wouldn't want to count ('abc',1) twice if it is in your table twice):
select count(distinct name)
from mytable
where type = 1
EDIT: for getting all types
select type, count(distinct name)
from mytable
group by type
order by type
select count(1) from tbl where type = 1
;WITH MyTable (Name, [Type]) AS
(
SELECT 'abc', 1
UNION
SELECT 'def', 2
UNION
SELECT 'ghi', 2
UNION
SELECT 'jkl', 1
UNION
SELECT 'mno', 1
)
SELECT COUNT( DISTINCT Name)
FROM MyTable
WHERE [Type] = 1

SQL - order by list order

I have the following query that returns rows based on a comma seperated list
Select * from Table where RecordID in (22,15,105,1,65,32)
I would like the results of this query to return to in the order of the ID's in the list. Is that possible with SQL?
Thanks in advance
select * from Table
where RecordID in (22,15,105,1,65,32)
order by (
case RecordID
when 22 then 1
when 15 then 2
when 105 then 3
when 1 then 4
when 65 then 5
when 32 then 6 end)
If you need the output to appear in a particular order, then you need to specify that order, using something the server can sort. Not knowing which engine you're working against, the general scheme would be to create a temp table or use rowset constructors to pair each record ID with its desired sort order.
E.g. (SQL Server)
declare #T table (RecordID int,Position int)
insert into #T (RecordID,Position)
select 22,1 union all
select 15,2 union all
select 105,3 union all
select 1,4 union all
select 65,5 union all
select 32,6
select * from Table t inner join #T t2 on t.RecordID = t2.RecordID order by t2.Position
I'd to the ordering in the client, but if you really want to do it in SQL, do it like this:
declare #T table (id int identity(1,1), RecordID int)
insert into #T (RecordID)
values (22), (15), (105), (1), (65), (32)
select * from
[table] t
inner join #t s on t.id=s.recordid
where t.id in (22, 15, 105, 1, 65, 32)
order by s.id
(works in SQL Server 2008)
Yes. You add the ORDER BY recordedid clause at the end.
The last time I had to do this I ended up doing a union all and generating a select statement for each id, i.e.
select * from Table where RecordID = 22
union all
select * from table where recordid = 15
etc.
It was a pain but it worked.
Use ORDER BY against the RecordID
Select * from Table where RecordID in (22,15,105,1,65,32) ORDER BY RecordID