Crosstab SQL query for 2 tables? [closed] - sql

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have 2 tables and I need to make one view of them like if it was 1 single table
Table1 DEVICE
+-----+-------+-----------+
|DevID|DevName|DevIP |
+-----+-------+-----------+
|1 |HH1 |192.168.1.1|
+-----+-------+-----------+
|2 |HH2 |192.168.1.2|
+-----+-------+-----------+
Table2 DEVICECUSTOMDATA
+-----+------------+--------+
|DevID|Name |Value |
+-----+------------+--------+
|1 |Model |CN70 |
+-----+------------+--------+
|1 |BuildVersion|1.2 |
+-----+------------+--------+
|1 |BuildDate |20140113|
+-----+------------+--------+
|2 |Model |MC55 |
+-----+------------+--------+
|2 |BuildVersion|1.2 |
+-----+------------+--------+
|2 |BuildDate |20140110|
+-----+------------+--------+
The resulting table should be:
+-----+-------+-----------+-----+------------+---------+
|DevID|DevName|DevIP |Model|BuildVersion|BuildDate|
+-----+-------+-----------+-----+------------+---------+
|1 |HH1 |192.168.1.1|CN70 |1.2 |20140113 |
+-----+-------+-----------+-----+------------+---------+
|2 |HH2 |192.168.1.2|MC55 |1.2 |20140110 |
+-----+-------+-----------+-----+------------+---------+
I would appreciate any help to do this. Thanks

SQL SERVER:
See SqlFiddle:
SELECT d.DevId, d.DevName, d.DevIp, p.Model, p.BuildVersion, p.BuildDate
FROM DEVICE d
JOIN (
SELECT *
FROM DEVICECUSTOMDATA
PIVOT (MAX(Value) FOR Name IN ([Model], [BuildVersion], [BuildDate])) as Something) p
on d.DevId = p.DevId

Working Online Example (SQL Server Syntax): SQL Fiddle
Result:
SQL Script:
DECLARE #Device TABLE (
DevID int not null,
DevName varchar(max) not null,
DevIP varchar(max) not null
)
insert into #Device values ('1', 'HH1','192.168.1.1')
insert into #Device values ('2', 'HH2','192.168.1.2')
DECLARE #DeviceCustomData TABLE (
CDevID int not null,
Name varchar(max) not null,
Value varchar(max) not null
)
insert into #DeviceCustomData
values ('1','Model','CN70')
insert into #DeviceCustomData
values ('1','BuildVersion','1.2')
insert into #DeviceCustomData
values ('1','BuildDate','20140113')
insert into #DeviceCustomData
values ('2','Model','MC55')
insert into #DeviceCustomData
values ('2','BuildVersion','1.2')
insert into #DeviceCustomData
values ('2','BuildDate','20140110')
SELECT *
FROM
(SELECT d.DevID, d.DevName, d.DevIP, c.Value, c.Name
FROM #Device d
inner join #DeviceCustomData c on d.DevID = c.CDevID) AS SourceTable
PIVOT(
MIN(Value)
FOR Name in ([Model],[BuildVersion],[BuildDate])
) as PivotTable
Reference: http://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

Related

Concise SQL for joining many tables on a single column

I have about 122 tables that all share a particular column. Is there an elegant/concise method to join all of these tables on that column without having 121 instances of
join on A.id = B.id
in the query?
If the column in question has the same name in both tables (which it should) then you can use this shorter syntax:
SELECT ... FROM table1 JOIN table2 USING (column)
The column will also appear only once in the result, instead of being present for each table. More details here.
You will still have to do it for each table, though.
Here goes your solution:
Create table and insert statement:
create table splitUpdate (no int,productname varchar(10),productcrossell varchar(20));
insert into splitUpdate values (1,'a','a(1)');
insert into splitUpdate values (2,null,'c(4),d(5)');
insert into splitUpdate values (3,null,'Z(1),b(2)');
create table eleminate (product varchar(20));
insert into eleminate values('x');
insert into eleminate values('y');
insert into eleminate values('Z');
insert into eleminate values('z');
Update Query:
with cte as (
select no,productname,p.product,row_number()over(partition by no)rn ,substring(p.product from 1 for position('(' in p.product )-1) SplittedProduct
from splitupdate t, unnest(string_to_array(t.productcrossell ,','))p(product)
where substring(p.product from 1 for position('(' in p.product )-1) not in (select product from eleminate))
update splitupdate set productname=splittedproduct
from cte
where splitupdate.productname is null and splitupdate.no=cte.no and cte.rn=1
SplitUpdate Table before updating:
|no|productname|productcrossell|
|1 |a |a(1) |
|2 |c |c(4),d(5) |
|3 |b |Z(1),b(2) |
Result:
|no|productname|productcrossell|
|1 |a |a(1) |
|2 |c |c(4),d(5) |
|3 |b |Z(1),b(2) |

Firebird insert into according to a condition [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
How can I insert a data from one table to another table according to a column condition
For example one table there is a column.if its value is 1 then insert
Database:Firebird 2.5
Based on the example you provided in your comment:
INSERT INTO some_table (CARI_id, anydatacomefromcari )
SELECT EFATURA_KULLAN, someotherdata FROM CARI
WHERE EFATURA_KULLAN = 1
fiddle example
Results:
The Script used for test is:
CREATE TABLE CARI (id INTEGER, EFATURA_KULLAN INTEGER, someotherdata INTEGER);
INSERT INTO CARI VALUES (1, 1, 55);
INSERT INTO CARI VALUES (2, 1, 44);
INSERT INTO CARI VALUES (3, 0, 99);
INSERT INTO CARI VALUES (4, 1, 12);
SELECT * FROM CARI;
CREATE TABLE some_table (CARI_id INTEGER, anydatacomefromcari INTEGER );
INSERT INTO some_table (CARI_id, anydatacomefromcari )
SELECT EFATURA_KULLAN, someotherdata FROM CARI
WHERE EFATURA_KULLAN = 1
SELECT * FROM some_table
Results:
+---------+-------------------------+
| CARI_id | anydatacomefromcari |
+---------+-------------------------+
| 1 | 55 |
+---------+-------------------------+
| 1 | 44 |
+---------+-------------------------+
| 1 | 12 |
+---------+-------------------------+

How to remove duplicate rows in postgresql? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I would like to remove duplicate entries in Postgresql.
There is no unique constraint, but I would like to consider all columns together to consider a row as a duplicate.
So we have a table containing following rows :
id | name | age | started_date |Score |
-----|----------|---------------|---------------|------|
1 | tom | 15 | 01/06/2022 |5 |
2 | tom | 15 | 01/06/2022 |5 |
3 | henry | 10 | 01/06/2022 |4 |
4 | john | 11 | 01/06/2022 |6 |
...
I would like to consider all columns together to identify the duplicate rows.
How to achieve this in Postgresql ?
PostgreSQL assigns a ctid pseudo-column to identify the physical location of each row. You could use that to identify different rows with the same values:
-- Create the table
CREATE TABLE my_table (num1 NUMERIC, num2 NUMERIC);
-- Create duplicate data
INSERT INTO my_table VALUES (1, 2);
INSERT INTO my_table VALUES (1, 2);
-- Remove duplicates
DELETE FROM my_table
WHERE ctid IN (SELECT ctid
FROM (SELECT ctid,
ROW_NUMBER() OVER (
PARTITION BY num1, num2) AS rn
FROM my_table) t
WHERE rn > 1);
DB Fiddle
Let say your table has 2 columns, you can identify duplicates using.
Post this :-
1) Insert this result into a temp table
2) Drop data from Main table
3) Insert data from temp table into main table
4) Drop temp table.
select col1, col2, count(*) as cnt
from table1
group by col1, col2
having cnt > 1

SQL Server : get size of longest value in column and include column name in that total

I have the following query that returns the number of the longest word it finds within that column:
SELECT
MAX(LEN(id)) AS id,
MAX(LEN(linkToTbl2)) AS linkToTbl2,
MAX(LEN(description)) AS description,
MAX(LEN(number)) AS number,
MAX(LEN(line)) AS line,
MAX(LEN(network)) AS network,
MAX(LEN(type)) AS type,
MAX(LEN(IPhase)) AS IPhase,
MAX(LEN(environment)) AS environment,
MAX(LEN(sType)) AS sType,
MAX(LEN(bDescription)) AS bDescription
FROM
bLine
However, if said column is smaller than the heading for that column then it doesn't take that into account when calculating the largest value.
Example (what I am looking to do):
|id | linkToTbl2 | description |
+---+------------+-------------------------+
|14 |hi |This is just a demo. |
|16 |baa |Another description here.|
Which would look like this in an example query:
|id |linkToTbl2 |description |
+---+-----------+------------+
|2 |10 |25 |
Now this is what it currently looks like in my SSRS report:
|id |lin|description |
| |kTo| |
| |tbl| |
| |2 | |
|---|---|-------------------------|
|14 |hi |This is just a demo. |
|16 |baa|Another description here.|
and this would look like this in the query:
|id |linkToTbl2 |description |
|---|-----------|------------|
|2 |3 |25 |
Notice how the linkToTbl2 field is compressed since the longest value in that column is 3 (baa). linkToTbl2 would be 10 (linkToTbl2) so it should be 10 and not 3.
How can I add the columns name into the query to count that as well?
You can use UNPIVOT and PIVOT
DECLARE #MyTable TABLE (id INT, linkToTbl2 VARCHAR(100), description VARCHAR(100))
INSERT INTO #MyTable VALUES
(14,'hi','This is just a demo.'),
(16,'baa','Another description here.')
SELECT * FROM
( SELECT
Col,
MAX(CASE WHEN LEN(Val) > LEN(Col) THEN LEN(Val) ELSE LEN(Col) END) LEN_OF_COL
FROM
( SELECT
CONVERT(VARCHAR(MAX),[Id]) [Id],
CONVERT(VARCHAR(MAX),[linkToTbl2]) [linkToTbl2],
CONVERT(VARCHAR(MAX),[description]) [description]
FROM #MyTable ) SRC
UNPIVOT (Val FOR Col IN( [Id], [linkToTbl2], [description] ) ) UNPVT
GROUP BY Col ) T
PIVOT( MAX(LEN_OF_COL) FOR Col IN ( [Id], [linkToTbl2], [description] ) ) PVT
Result:
Id linkToTbl2 description
----------- ----------- -----------
2 10 25
If your columns are all strings, you could use the rather brute force:
select . . .
from ((select id, linkToTbl2, . . . from bLine) union all
(select 'id', 'linkToTbl2', . . .)
) b;
Whatever approach you take in SQL will require listing all the column names. I think this is better done in the application layer.

Translate rows to column [duplicate]

This question already has answers here:
Efficiently convert rows to columns in sql server
(5 answers)
Closed 7 years ago.
I have a few items in the database in the form as below:
ID|ColName|ColValue
-------------------
1 |A |1testa
1 |B |1testb
1 |C |1testc
1 |D |1testd
2 |A |2testa
2 |D |2testd
I need data in the form below:
ID| A | B | C | D
1 | 1testa | 1testb | 1testc | 1testd
2 | 2testa | NULL | NULL | 2testd
I have tried using PIVOT in T-SQL but it takes aggregate function as argument, which I do not want to supply.
How can I achieve this.
The following code:
DECLARE #DataSource TABLE
(
[ID] TINYINT
,[ColName] CHAR(1)
,[ColValue] VARCHAR(12)
);
INSERT INTO #DataSource ([ID], [ColName], [ColValue])
VALUES (1, 'A', '1testa')
,(1, 'B', '1testb')
,(1, 'C', '1testc')
,(1, 'D', '1testd')
,(2, 'A', '2testa')
,(2, 'D', '2testd');
SELECT *
FROM #DataSource
PIVOT
(
MAX([ColValue]) FOR [ColName] IN ([A], [B], [C], [D])
) PVT
is going to give you this:
Note, that when you are using the PIVOT/UNPIVOT clauses, you need to specified the columns (in your case A, B, C, D). If you do not want to hard-coded then, you need to build a dynamic pivot using - this can be done building the T-SQL statement in a string and executing it using sp_executesql.