how to convert my colums data to rows in sql server - sql-server-2008-r2

I am working on an online exam database in sql server where i have one table with following structure :-
id question option1 option2 option3 option4 option1_image option2_image option3_image option4_image
and i want data in following format
id options option_image
in option column, i want to get all options value and in option_image column i want all images. i am using following query
select id,Options,Option_Image
from Questions
unpivot
(
Options
for col in (option1, option2,option3,option4)
) u
unpivot
(
Option_Image
for img in(option1_image,option2_image,option3_image,option4_image)
) v
But it dosnt work

I don't know if this is good for large amount of record
but you can try this
select ID,option1,option1_img from Questions
union all
select ID,option2,option2_img from Questions
union all
select ID,option3,option3_img from Questions
union all
select ID,option4,option4_img from Questions

Related

Db2 convert rows to columns

I need the below results ..
Table :
Order postcode qnty
123 2234 1
Expected result:
Order 123
Postcode 2234
Qnty 1
SQL server:
Select pvt.element_name
,pvt.element_value(select order.postcode
from table name)up
unpivot (element_value for element_name in(order,postcode) as Pvt
How to achieve this in db2?
Db2 for IBM i doesn't have a built-in unpviot function.. AFAIK, it's not available on any Db2 platofrm...unless it's been added recently.
The straight forward method
select 'ORDER' as key, order as value
from mytable
UNION ALL
select 'POSTCODE', postcode
from mytable
UNION ALL
select 'QNTY', char(qnty)
from mytable;
A better performing method is to do a cross join between the source table and a correlated VALUES of as many rows as columns that need to be unpivoted.
select
Key, value
from mytable T,
lateral (values ('ORDER', t.order)
, ('POSTCODE', t.postcode)
, ('QNQTY', varchar(t.qnty))
) as unpivot(key, value);
However, you'll need to know ahead of time what the values you're unpivoting on.
If you don't know the values, there are some ways to unpivot with the XMLTABLE (possibly JSON_TABLE) that might work. I've never used them, and I'm out of time to spend answering this question. You can find some examples via google.
I have created a stored procedure for LUW that rotate a table:
https://github.com/angoca/db2tools/blob/master/pivot.sql
You just need to call the stored procedure by passing the tablename as parameter, and it will return a cursor with the headers of the column in the first column.

Combine count and max in postgresql sql

I have a problem to formulate an sql question in postgresql, hoping to get some help here
I have a table called visitor that contains an column called fk_employee_id, fk_employee_id contains different number between 1-10, example:
1,3,4,6,4,6,7,3,2,1,6,7,6
Now I want to find out which value that is the most frequent in this column (in this case 6) I have made an question that seem to solve my question;
SELECT fk_employee_id
FROM visitor
GROUP BY fk_employee_id
ORDER BY COUNT(fk_employee_id) DESC
LIMIT 1
but this question, doesn't get right if it is two values that are the most frequent one. So instead I try to write a question which contains max function but cant figure out how, anyone now how to do this?
We can use RANK here to slightly modify your current query:
WITH cte AS (
SELECT
fk_employee_id,
RANK() OVER (ORDER BY COUNT(*) DESC) rank
FROM visitor
GROUP BY fk_employee_id
)
SELECT fk_employee_id
FROM cte
WHERE rank = 1;
Demo

How to combine multiple columns into one in postgresql using row_to_json

I have table with 3 columns:
id|name|geometry
-----------------
1 |xie|geometry
i want to get the geometry in geojson format.
select id,name,ST_AsGEOJSON(geom) from table;
`o/p : `'{"id":"1","name":"xie","type":"Polygon","coordinates"[[[103.349002218076,-4.79402531349065]]]}'`
then i am using row_to_json to combine the columns:
SELECT row_to_json(t) from (SELECT id,name,ST_AsGEOJSON(geom) from table where id=1)t
this command is changing the original output as:
o/p :`'{"id":"1","name":"xie","st_asgeojson":"{\"type\":\"Polygon\",\"coordinates\":[[[102.325742539781,-3.83353755877152]]]}"}'`
but i want to combine the columns without any change in the original output.How can i do that?
You have two choices:
1) You build a json with the geometry as geojson but expressed as string (without quotes):
SELECT row_to_json(t) FROM (
SELECT id,name,replace(ST_AsGEOJSON(geom),'"','') AS geom
FROM table where id=1
) AS t;
Result:
{"id":1,"name":"xie","geom":"{type:Polygon,coordinates:[[[0,0],[0,1],[1,1],[1,0],[0,0]]]}"}
2) Build a json with a legal geojson geometry. Appending a json to another is unfortunately not really supported (yet) by Postgres. You have to build the Json manually:
SELECT (format(
'{"id":%s,"name":%s,"geom":%s}', to_json(id), to_json(name),st_asgeojson(geom))
)::json from table where id=1;
Result:
{"id":1,"name":"xie","geom":{"type":"Polygon","coordinates":[[[0,0],[0,1],[1,1],[1,0],[0,0]]]}}

Line numbering in result grid in MySQL Workbench

Is there any way to add some line numbers in the result grid in MySQL Workbench?
E.g. (red numbers):
I don't want to have to change the SQL query, which I know I can do using tricks like
SELECT #n := #n + 1 `Number of Submissions`, t.*
FROM (SELECT #n:=0) initvars,
( SELECT COUNT(*) AS count
FROM moocdb.submissions
GROUP BY user_id
ORDER BY count DESC
) t
I also don't want to have to export the results.
Not sure if that is a good question for SO, but anyway: no this is not possible. Nobody asked for that so far, so, file a feature request at http://bugs.mysql.com to have that in.
MySQL does not provide row_number like Microsoft SQL Server, Oracle, or PostgreSQL. Fortunately, MySQL provides session variables that you can use to emulate the row_number function.
SET #row_number = 0;
SELECT (#row_number:=#row_number + 1) AS num, col_1
FROM
Table

Hive: How to do a SELECT query to output a unique primary key using HiveQL?

I have the following schema dataset which i want to transform into a table that can be exported to SQL. I am using HIVE. Input as follows
call_id,stat1,stat2,stat3
1,a,b,c,
2,x,y,z,
3,d,e,f,
1,j,k,l,
The output table needs to have call_id as its primary key so it needs to be unique. The output schema should be
call_id,stat2,stat3,
1,b,c, or (1,k,l)
2,y,z,
3,e,f,
The problem is that when i use the keyword DISTINCT in the HIVE query, the DISTINCT applies to the all the colums combined. I want to apply the DISTINCT operation only to the call_id. Something on the lines of
SELECT DISTINCT(call_id), stat2,stat3 from intable;
However this is not valid in HIVE(I am not well-versed in SQL either).
The only legal query seems to be
SELECT DISTINCT call_id, stat2,stat3 from intable;
But this returns multiple rows with same call_id as the other columns are different and the row on the whole is distinct.
NOTE: There is no arithmetic relation between a,b,c,x,y,z, etc. So any trick of averaging or summing is not viable.
Any ideas how i can do this?
One quick idea,not the best one, but will do the work-
hive>create table temp1(a int,b string);
hive>insert overwrite table temp1
select call_id,max(concat(stat1,'|',stat2,'|',stat3)) from intable group by call_id;
hive>insert overwrite table intable
select a,split(b,'|')[0],split(b,'|')[1],split(b,'|')[2] from temp1;
,,I want to apply the DISTINCT operation only to the call_id"
But how will then Hive know which row to eliminate?
Without knowing the amount of data / size of the stat fields you have, the following query can the job:
select distinct i1.call_id, i1.stat2, i1.stat3 from (
select call_id, MIN(concat(stat1, stat2, stat3)) as smin
from intable group by call_id
) i2 join intable i1 on i1.call_id = i2.call_id
AND concat(i1.stat1, i1.stat2, i1.stat3) = i2.smin;