whether to use pivot or non-pivot without any aggregate function - sql-server-2014

I got two tables table 1 and 2 as shown below. I need to insert the Std_rid for the row which has A and its corresponding Act_rid present in table 2 in resultant table 3. I'm only using the sample here. I'm very confused whether to use pivot or unpivot here. Any help appreciated. Thanks
Table 1
----------
G_Standard N_Standard Skill One_for_all Am_Water B2Future Std_rid
ELW.6 Lit.W.K.6 Writing A 1
ELW.8 Lit.W.K.8 Writing A 2
ELW.7 Lit.W.K.7 Writing A 3
Table 2
----------
Act_rid Act_Desc date createdby
3 Am_Water 2/4/15 sys
6 B2Future 2/4/15 sys
1 One_for_all 2/14/15 sys
Output Result Table 3
----------
ID Std_rid Act_rid
1 1 3
2 2 6
3 3 1

This is an UNPIVOT. UNPIVOT turns columns into rows.
;WITH Unpivot_Table_1 AS (
SELECT Std_rid,
Act_Desc
FROM [Table 1]
UNPIVOT (Value FOR Act_Desc IN ([One_for_all],[Am_Water],[B2Future])) u
WHERE u.Value = 'X'
)
SELECT ROW_NUMBER() OVER(ORDER BY t1.Std_rid) AS ID,
t1.Std_rid,
t2.Act_rid
FROM Unpivot_Table_1 t1
JOIN [Table 2] t2
ON t2.Act_Desc = t1.Act_Desc;
I hope this is something for data integration. Otherwise, y'all need to shoot whomever designed this.
Test data:
CREATE TABLE dbo.[Table 1]
(
Std_rid INT NOT NULL PRIMARY KEY,
One_for_all VARCHAR(1),
Am_Water VARCHAR(1),
B2Future VARCHAR(1)
);
INSERT INTO dbo.[Table 1] (Std_rid,One_for_all,Am_Water,B2Future)
VALUES
(1,NULL,'X',NULL),
(2,NULL,NULL,'X'),
(3,'X',NULL,NULL);
CREATE TABLE dbo.[Table 2]
(
Act_rid INT NOT NULL PRIMARY KEY,
Act_Desc VARCHAR(30)
);
INSERT INTO dbo.[Table 2] (Act_rid,Act_Desc)
VALUES
(3,'Am_Water'),
(6,'B2Future'),
(1,'One_for_all');

Related

SSRS How to return column name of the column which have max value

I have a table with only column head and 1 row like below
>>> table
Out[1]:
A_Spd1 A_Spd2 A_Spd3 B_Spd1 B_Spd2 B_Spd3 C_Spd1 C_Spd2
10 5 7 2 4 8 6 2
Is there anyway I can do comparison between column and return column with max value ?
For example: A_spd1=10, B_spd1=2, C_spd1=9 --> The function should return name "A_spd1"
Thanks and best regards
There maybe be a much more elegant way to do this but this is straight forward. The first part just recreates your data..
--re-create your sample table
DECLARE #t TABLE(A_Spd1 int, A_Spd2 int, A_Spd3 int, B_Spd1 int, B_Spd2 int, B_Spd3 int, C_Spd1 int, C_Spd2 int, C_Spd3 int)
INSERT INTO #t SELECT 10,5,7,2,4,8,9,2,6
-- now do the query
-- first unpivot the data so we have 2 columns, colName and colValue
;WITH
UnPivTable as (
SELECT * FROM #t
UNPIVOT (
ColValue FOR ColName IN ([A_Spd1], [A_Spd2], [A_Spd3], [B_Spd1], [B_Spd2], [B_Spd3], [C_Spd1], [C_Spd2], [C_Spd3])
) AS U
)
-- now just select all records where the colValue equals the MAX colValue
SELECT * from UnPivTable
WHERE ColValue = (SELECT MAX(ColValue) FROM UnPivTable)
This answer assumes that the column names are always the same.
It also assumes that two columns can contain the same highest number, in this case both column names are returned.

Use value of column as table name in subquery mysql

Hi I am new to mysql I am trying to to create a query where the subquery table name is based in value of column name
I got three table as sample only can be more
first table named main
Main
id tbl val
1 t 2
2 r 1
Next table named t
name
ana
jjj
Next table named r
name
ana
hyu
Desired out put
I tried this query but not working sql syntax erro
id tbl val test
1 t 2 exist
2 r 1 not
Select id, tbl, val, #tblname := tbl,
isnull((select 'exist' from #tblname where name="jjj" limit 1), "not") as test
from main
will really appreciate any advise or help thank you

Is it possible to declare data type for each column of a Pivoted Table in MySQL?

I happened to have dynamic data with a group of common IDs. So I decided to create a Pivot table for it. Let's say I've a following data in before I create a pivot table.
part_id data_element value
------------------------------------------------
part1 part_name Motor
part1 operator_id Kishore
part1 shift_id B
part1 production_count 20
part2 part_name LVDT
part2 operator_id Kumar
part2 shift_id A
part2 production_count 3
As you can see in the above table, for a part1, I've different data_elements and their respective values. And I had to make varchar as a common data type for value column since value could be anything. And based on this, I created the following pivot table.
part_id part_name operator_id shift_id production_count
-----------------------------------------------------------
part1 Motor Kishore B 20
part2 LVDT Kumar A 3
Please find pivoting queries I've used to achieve the above pivoted table
CREATE VIEW table_view_name AS (
SELECT
`table_name`.`part_id`,
`table_name`.`data_element`,
`table_name`.`value`,
(CASE WHEN (`table_name`.`data_element` = 'part_name') THEN
`table_name`.`value` END) AS `part_name`,
(CASE WHEN (`table_name`.`data_element` = 'operator_id') THEN
`table_name`.`value` END) AS `operator_id`,
(CASE WHEN (`table_name`.`data_element` = 'shift_id') THEN
`table_name`.`value` END) AS `shift_id`,
(CASE WHEN (`table_name`.`data_element` = 'production_count') THEN
`table_name`.`value` END) AS `production_count`
FROM `table_name`)
And
CREATE VIEW `table_extended_view` AS (
SELECT
`table_view_name`.`part_id`,
MAX(`table_view_name`.`part_name`) AS `part_name`,
MAX(`table_view_name`.`operator_id`) AS `operator_id`,
MAX(`table_view_name`.`shift_id`) AS `shift_id`,
MAX(`table_view_name`.`production_count`) AS `production_count`
FROM `table_view_name`
GROUP BY `table_view_name`.`part_id`)
But here, although all columns and their values have been segregated, the data type for each column is varchar only. So here my only question is, Can I change the data type of a column in pivot table? If so, How could it be?

MySQL One-to-Many: Select where only one relations exists

My Tables:
CREATE TABLE `binary` (
`binaryid` int(15) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`binaryid`)
);
CREATE TABLE `binarycollection` (
`binaryid` int(10) unsigned NOT NULL,
`collectionid` int(10) unsigned NOT NULL,
UNIQUE KEY `collectionid` (`collectionid`,`binaryid`),
KEY `binaryid` (`binaryid`)
);
In the binary table there can only exist one record to a binaryid.
The binarycollection table ties the binary to multiple collections.
What I need to do is make a query that will select all rows in binary that have exactly 1 relations in binarycollection.
So given the example:
binary:
1
2
3
4
5
6
7
binarycollection:
(binaryid collectionid)
1 1
2 1
3 1
3 2
4 1
4 2
5 2
6 2
It should return binaryids 1, 2, 5, and 6.
Any help is appreciated. :)
ps. This needs to be efficient, the tables contain millions of rows.
Use GROUP BY :
Select binaryid from binarycollection group by binaryid having count(*)=1
It should work out to a simple query since your referential integrity doesn't allow repeat pairs in the binarycollection table:
SELECT binaryid
FROM binarycollection
GROUP BY binaryid
HAVING ( COUNT(binaryid) = 1 )
join it with the original binary table to check for valid reference then group the binaryID
SELECT a.binaryid
FROM `binary` a
INNER JOIN `binarycollection` b
on a.binaryid = b.binaryid
GROUP BY a.binaryid
HAVING COUNT(a.binaryid) = 1

sql server - getting values from one table with columns' names stored in another table

I have several tables. These are somewhat simplified versions of the tables:
UsersTable:
UserId FirstName LastName MiddleInit Suffix Age Position
1 John Graham P. Jr. 35 Analyst II
2 Bill Allen T. III 45 Programmer I
3 Jenny Smith K. 25 Systems Engineer
4 Gina Todd J. 55 Analyst II
TableTypes:
TableTypeId TableType
1 Names
2 Positions
3 Age
TableTypeId is primary key in TableTypes and foreign key in TableFields.
TableFields:
FieldId TableTypeId FieldName Description
1 1 FirstName descr1
2 1 LastName descr2
3 1 MiddleInit descr3
4 1 Suffix descr4
FieldId is primary key in TableFields and foreign key in ModifiedUsersTable.
I need to fill ModifiedUsersTable with values from UsersTable so it looks like this:
ModifiedUsersTable:
Id UserId FieldId Value
1 1 1 John
2 1 2 Graham
3 1 3 P.
4 1 4 Jr.
5 2 1 Bill
etc.
I need to get only those columns from UsersTable that are listed in FieldName column in the TableFields table. I don't know the number of rows (fieldNames) or the names in advance in the TableFields.
I thought I should try to use PIVOT. I can get a comma separated string of the column names and then dynamically convert them into columns.
But it doesn't seem to give me what I need. How do I fill ModifiedUsersTable?
Any suggestions?
Thanks!
DDL for your data
create table UsersTable(
UserId int, FirstName varchar(100), LastName varchar(100), MiddleInit varchar(100),
Suffix varchar(100), Age int, Position varchar(100));
insert UsersTable select
'1','John','Graham','P.','Jr.','35','Analyst II' union all select
'2','Bill','Allen','T.','III','45','Programmer I' union all select
'3','Jenny','Smith','K.',null,'25','Systems Engineer' union all select
'4','Gina','Todd','J.',null,'55','Analyst II';
create table tabletypes(
TableTypeId int, TableType varchar(100));
insert tabletypes select
1, 'Names' union all select
2, 'Positions' union all select
3, 'Age';
create table TableFields(
FieldId int,TableTypeId int,FieldName varchar(100),Description varchar(100));
insert TableFields select
'1','1','FirstName','descr1' union all select
'2','1','LastName','descr2' union all select
'3','1','MiddleInit','descr3' union all select
'4','1','Suffix','descr4';
create table ModifiedUsersTable(
Id int identity, userid int, fieldid int, value varchar(max));
The script to populate ModifiedUsersTable
declare #sql nvarchar(max)
select #sql = coalesce(#sql+ '
union all
', '') + '
select userid,' + right(FieldId,12) + ',' + quotename(fieldname) + '
from userstable'
from tablefields
set #sql = #sql + '
order by userid, 2'
-- print #sql -- uncomment to see the generated SQL
exec (#sql)