Replace row with Column Data in Sql Server - sql

I have a table with some data and I was trying to Replace the Column with Row.
SELECT Handset_UID, [IMEI_NO_1] AS [IMEI #1],[IMEI_NO_2] AS [IMEI #2],
Isnull(Convert(varchar,Mfg_Date,106),'Not Found') as [Mfg. Date]
FROM stock.Handset a
join Stock.Model b
on a.Model_ID = b.Model_ID
JOIN Stock.Brand C
ON A.Brand_ID = C.Brand_ID
where a.Handset_UID = 'GFI13508637275434'
The above Query gives me the result in one single row data.
But I want the Result in below format
I have tried the Pivot Operator using Derived Column but got confused during implementation.
Please help to get the correct query.

Assuming that you are running SQL Server, as the syntax suggests, you can unpivot with cross apply:
select x.col, x.val
from stock.handset h
inner join stock.model m on h.model_id = m.model_id
inner join stock.brand b on on h.brand_id = b.brand_id
cross apply (values
('handset_uid', handset_uid),
('IMEI #1', imei_no_1),
('IMEI #2', imei_no_2),
('Mfg.Date', convert(varchar, Mfg_Date, 106), 'Not Found')
) x(col, val)
where h.handset_uid = 'gfi13508637275434'
Side notes:
meaningful table aliases make the query easier to read and write
your query has many columns that are not qualified with the alias of the table they belong to, which makes your query rather unclear about the underlying structure; I would strongly recommend that you qualify all columns in the query

Related

Multiple results into one SQL

I have a database and when I grab some results I want to work out how to return in a different format to what I am getting now for example
select
reports.host_ip, reportitems.mskb
from
reportitems
inner join
reports on reports.report_id = reportitems.report_id
where
reportitems.mskb IS NOT NULL
order by
reportitems.mskb;
Output:
10.63.128.115|2251481
10.63.128.89|2269637
10.63.128.100|2269637
10.63.128.16|2269637
10.63.128.115|2269637
10.63.128.115|2669970
10.63.128.89|2871997
10.63.128.100|2871997
10.63.128.16|2871997
10.63.128.115|2871997
10.63.128.194|3000483
10.63.128.198|3000483
10.63.128.89|3000483
I would like the output to be for example all of the ips in the left column to be grouped so for 2269637 it would look like
10.63.128.89
10.63.128.100 2269637
10.63.128.16
10.63.128.115
can I do that with the SQL statement or will i need to process that afterwards?
Thanks
Generally this would be left up to the UI displaying the data, but if that isn't an option, or it's just difficult to implement, you could use the GROUP_CONCAT() function and shove a carriage return in between values:
SELECT GROUP_CONCAT(CONCAT(reports.host_ip, '\n')) as IP_Addresses,
reportitems.mskb
FROM reportitems
INNER JOIN reports
ON reports.report_id = reportitems.report_id
WHERE reportitems.mskb IS NOT NULL
GROUP BY reportitems.mskb
ORDER BY reportitems.mskb

SQL Query (Oracle SQL)

I need a little help with the following SQL Query:
SELECT AUF_EK.FIRM, AUF_EK.customer, AUF_EK.cnr, k.name1,
k.name2, k.name3, k.street, k.pin, k.loc, r.name1,
r.name2, r.name3, lo_gpname1,
.....
First the selected columns, I get that so far.
FROM AUFT, PARTNER r, PARTNER k, .... skp_ARTIKEL_Z,
then we have the from clause, but why is there an Partner r and Partner k? Does it mean the table name is "Partner r" or is the a other reason I don't know yet?
WHERE (
AUF.FIRM BETWEEN 123 AND 456 AND AUF.FIRM = k.FIRM AND AUF.customer = k.gpnr AND AUF.FIRM
= k.FIRM AND AUF.customer = k.gpnr AND AUF.art_nr = ART.art_nr
The where clause makes sense to me till here, so it basically matches columns from the selected tables...
AND EK_POS.art_nr =
ARTIKEL_Z.art_nr(+) AND NVL
(POS.pos_nr_zuo, 0) = (NVL (
_EK_POS_PREIS.pos_nr_zuo(+), 0)) )
But here the part I don't get. I'm not an SQL Pro.... What does the (+) is doing? And what is ,0 meaning?
Partner r and Partner k
You can refer this answer What's the best way to join on the same table twice?
What does the (+) is doing?
Refer the answer of OMG Ponies
That's Oracle specific notation for an OUTER JOIN, because the ANSI-89 format (using a comma in the FROM clause to separate table references) didn't standardize OUTER joins.
The query would be re-written in ANSI-92 syntax as:
SELECT ...
FROM a
LEFT JOIN b ON b.id = a.id
It should also be noted that even though the (+) works, Oracle recommends not using it
And what is ,0 meaning?
NVL(POS.pos_nr_zuo, 0) if value of POS.pos_nr_zuo is null, it return 0 as default value
You asked several questions:
about the PARTNER r:
In your query you want to reference the table PARTNER twice, so you give it an alias, first one is r,second is k.
It's hard to say what exactly it's used for because I can't see the whole query. But a simple example is : suppose you have a ADDRESSES table and an ORDERS table. ORDERS has two references to people : BILLING_ADDR_ID and SHIPPING_ADDR_ID. If you want to display both addresses in a query, you need two aliases.
About the (+) - It's an old syntax for LEFT OUTER JOIN.
About the ',0 - It's part of the NVL(...,0) expression.

Why am i getting Unknown column 'list_class.pk_class_id' in 'on clause' error?

I want to get student details from different tables with given academic year and class.
Query that i used is:
SELECT
list_acad_years.acad_year,
a.fk_stu_id,
tbl_stu_details.stu_fname,
tbl_stu_details.stu_sname,
a.fk_section_id,
b.fk_class_id,
list_class.class_name,
list_sections.section_code
FROM
tbl_stu_details,
list_class,
list_sections,
list_acad_years
INNER JOIN
tbl_stu_class AS a
ON
(
list_acad_years.pk_acad_year_id = a.fk_year_id
)
INNER JOIN
tbl_stu_class AS b
ON
(list_class.pk_class_id = b.fk_class_id)
WHERE
(
list_acad_years.acad_year = '2019'
) AND(list_class.class_name = '10')
it shows the following error:
#1054 - Unknown column 'list_class.pk_class_id' in 'on clause'
columns of my table are:
tbl_stu_class:
pk_stu_cls_id`, `fk_stu_id`, `fk_year_id`, `fk_class_id`, `fk_section_id`, `current_yr`
list_class:
`pk_class_id`, `class_name`, `class_code`, `fk_user_id`
list_sections:
pk_section_id`, `section_code`, `section_description`, `fk_user_id`
list_acad_years:
`pk_acad_year_id`, `acad_year`, `acad_year_code`, `fk_user_id`
tbl_stu_details:
`pk_stu_id`, `stu_id`, `username`, `stu_fname`, `stu_mname`, `stu_sname`
list_sections:
`pk_section_id`, `section_code`, `section_description`, `fk_user_id`
Why did it say unknown column when the column is present?
It would be great help if you can help me make this query better...
Thanks in advance.
Your problem is that you are using old-style joins. Period. To make matters worse, you are combining them with new style joins.
The names of the tables are not understood across commas. That limits the scope of the definitions.
You appear to know how to write JOINs correctly. So, just fix the FROM clause and your code should work.
Your Inner join will alway connect to the last table in from statement if you are using multiple FROM table.
I have just change the position of INNER JOIN
try this let me know if it works.
SELECT
list_acad_years.acad_year,
a.fk_stu_id,
tbl_stu_details.stu_fname,
tbl_stu_details.stu_sname,
a.fk_section_id,
b.fk_class_id,
list_class.class_name,
list_sections.section_code
FROM
tbl_stu_details,
list_class INNER JOIN
tbl_stu_class AS b
ON
(list_class.pk_class_id = b.fk_class_id),
list_sections,
list_acad_years
INNER JOIN
tbl_stu_class AS a
ON
(
list_acad_years.pk_acad_year_id = a.fk_year_id
)
WHERE
(
list_acad_years.acad_year = '2019'
) AND(list_class.class_name = '10')

How can I do a SQL join to get a value 4 tables farther from the value provided?

My title is probably not very clear, so I made a little schema to explain what I'm trying to achieve. The xxxx_uid labels are foreign keys linking two tables.
Goal: Retrieve a column from the grids table by giving a proj_uid value.
I'm not very good with SQL joins and I don't know how to build a single query that will achieve that.
Actually, I'm doing 3 queries to perform the operation:
1) This gives me a res_uid to work with:
select res_uid from results where results.proj_uid = VALUE order by res_uid asc limit 1"
2) This gives me a rec_uid to work with:
select rec_uid from receptor_results
inner join results on results.res_uid = receptor_results.res_uid
where receptor_results.res_uid = res_uid_VALUE order by rec_uid asc limit 1
3) Get the grid column I want from the grids table:
select grid_name from grids
inner join receptors on receptors.grid_uid = grids.grid_uid
where receptors.rec_uid = rec_uid_VALUE;
Is it possible to perform a single SQL that will give me the same results the 3 I'm actually doing ?
You're not limited to one JOIN in a query:
select grids.grid_name
from grids
inner join receptors
on receptors.grid_uid = grids.grid_uid
inner join receptor_results
on receptor_results.rec_uid = receptors.rec_uid
inner join results
on results.res_uid = receptor_results.res_uid
where results.proj_uid = VALUE;
select g.grid_name
from results r
join resceptor_results rr on r.res_uid = rr.res_uid
join receptors rec on rec.rec_uid = rr.rec_uid
join grids g on g.grid_uid = rec.grid_uid
where r.proj_uid = VALUE
a small note about names, typically in sql the table is named for a single item not the group. thus "result" not "results" and "receptor" not "receptors" etc. As you work with sql this will make sense and names like you have will seem strange. Also, one less character to type!

Subselect a Summed col in Oracle

this is an attempted fix to a crystal reports use of 2 sub reports!
I have a query that joins 3 tables, and I wanted to use a pair of sub selects that bring in the same new table.
Here is the first of the two columns in script:
SELECT ea."LOC_ID", lo."DESCR", ea."PEGSTRIP", ea."ENTITY_OWNER"
, ea."PCT_OWNERSHIP", ea."BEG_BAL", ea."ADDITIONS", ea."DISPOSITIONS"
, ea."EXPLANATION", ea."END_BAL", ea."NUM_SHARES", ea."PAR_VALUE"
, ag."DESCR", ea."EOY", ea."FAKEPEGSTRIP",
(select sum(htb.END_FNC_CUR_US_GAAP)
from EQUITY_ACCOUNTS ea , HYPERION_TRIAL_BALANCE htb
where
htb.PEGSTRIP = ea.PEGSTRIP and
htb.PRD_NBR = 0 and
htb.LOC_ID = ea.LOC_ID and
htb.PRD_YY = ea.EOY
) firstHyp
FROM ("TAXPALL"."ACCOUNT_GROUPING" ag
INNER JOIN "TAXP"."EQUITY_ACCOUNTS" ea
ON (ag."ACCT_ID"=ea."PEGSTRIP") AND (ag."EOY"=ea."EOY"))
INNER JOIN "TAXP"."LOCATION" lo ON ea."LOC_ID"=lo."LOC_ID"
WHERE ea."EOY"=2009
ORDER BY ea."LOC_ID", ea."PEGSTRIP"
When this delivers the dataset the value of "firstHyp" fails to change by pegstrip value. It returns a single total for the join and fails to put the proper by value by pegstrip.
I thought that the where clause would have picked up the joins line by line.
I don't do Oracle syntax often so what am I missing here?
TIA
Your SQL is equivilent to the following:
SELECT ea."LOC_ID", lo."DESCR", ea."PEGSTRIP",
ea."ENTITY_OWNER" , ea."PCT_OWNERSHIP",
ea."BEG_BAL", ea."ADDITIONS", ea."DISPOSITIONS" ,
ea."EXPLANATION", ea."END_BAL", ea."NUM_SHARES",
ea."PAR_VALUE" , ag."DESCR", ea."EOY", ea."FAKEPEGSTRIP",
(select sum(htb.END_FNC_CUR_US_GAAP)
from EQUITY_ACCOUNTS iea
Join HYPERION_TRIAL_BALANCE htb
On htb.PEGSTRIP = iea.PEGSTRIP
and htb.LOC_ID = iea.LOC_ID
and htb.PRD_YY = iea.EOY
where htb.PRD_NBR = 0 ) firstHyp
FROM "TAXPALL"."ACCOUNT_GROUPING" ag
JOIN "TAXP"."EQUITY_ACCOUNTS" ea
ON ag."ACCT_ID"=ea."PEGSTRIP"
AND ag."EOY"=ea."EOY"
JOIN "TAXP"."LOCATION" lo
ON ea."LOC_ID"=lo."LOC_ID"
WHERE ea."EOY"=2009
ORDER BY ea."LOC_ID", ea."PEGSTRIP"
Notice that the subquery that generates firstHyp is not in any way dependant on the tables in the outer query... It is therefore not a Correllated SubQuery... meaning that the value it generates will NOT be different for each row in the outer query's resultset, it will be the same for every row. You need to somehow put something in the subquery that makes it dependant on the value of some row in the outer query so that it will become a correllated subquery and run over and over once for each outer row....
Also, you mention a pair of subselects, but I only see one. Where is the other one ?
Use:
SELECT ea.LOC_ID,
lo.DESCR,
ea.PEGSTRIP,
ea.ENTITY_OWNER,
ea.PCT_OWNERSHIP,
ea.BEG_BAL,
ea.ADDITIONS,
ea.DISPOSITIONS,
ea.EXPLANATION,
ea.END_BAL,
ea.NUM_SHARES,
ea.PAR_VALUE,
ag.DESCR,
ea.EOY,
ea.FAKEPEGSTRIP,
NVL(SUM(htb.END_FNC_CUR_US_GAAP), 0) AS firstHyp
FROM TAXPALL.ACCOUNT_GROUPING ag
JOIN TAXP.EQUITY_ACCOUNTS ea ON ea.PEGSTRIP = ag.ACCT_ID
AND ea.EOY = ag.EOY
AND ea.EOY = 2009
JOIN TAXP.LOCATION lo ON lo.LOC_ID = ea.LOC_ID
LEFT JOIN HYPERION_TRIAL_BALANCE htb ON htb.PEGSTRIP = ea.PEGSTRIP
AND htb.LOC_ID = ea.LOC_ID
AND htb.PRD_YY = ea.EOY
AND htb.PRD_NBR = 0
GROUP BY ea.LOC_ID,
lo.DESCR,
ea.PEGSTRIP,
ea.ENTITY_OWNER,
ea.PCT_OWNERSHIP,
ea.BEG_BAL,
ea.ADDITIONS,
ea.DISPOSITIONS,
ea.EXPLANATION,
ea.END_BAL,
ea.NUM_SHARES,
ea.PAR_VALUE,
ag.DESCR,
ea.EOY,
ea.FAKEPEGSTRIP,
ORDER BY ea.LOC_ID, ea.PEGSTRIP
I agree with Charles Bretana's assessment that the original SELECT in the SELECT clause was not correlated, which is why the value never changed per row. But the sub SELECT used the EQUITY_ACCOUNTS table, which is the basis for the main query. So I removed the join, and incorporated the HYPERION_TRIAL_BALANCE table into the main query, using a LEFT JOIN. I wrapped the SUM in an NVL rather than COALESCE because I didn't catch what version of Oracle this is for.