How to use WHERE in VIEW? - sql

In myView in the database, I have:
SELECT orderhdr3_.id AS col_0_0_,
gnrlorg2_.id AS col_1_0_,
gnrlorg2_.name AS col_2_0_,
gnrlcustom1_.id AS col_3_0_,
gnrlcustom1_.name AS col_4_0_,
orderhdr3_.order_no AS col_5_0_,
orderhdr3_.cust_ref_no AS col_6_0_,
tripinfo4_.job_no AS col_7_0_,
orderhdr3_.order_type AS col_8_0_,
servicetyp5_.code AS col_9_0_,
tripinfo4_.service_provider_id AS col_10_0_,
tripinfo4_.service_personnel AS col_11_0_,
orderhdr3_.status AS col_12_0_,
orderhdr3_.completed_date AS col_13_0_,
orderhdr3_.reason_code AS col_14_0_,
orderhdr3_.remarks AS col_15_0_,
orderhdr3_.source_order_hdr_location_id AS col_16_0_,
orderhdrlo7_.unit_no AS col_17_0_,
orderhdrlo7_.name AS col_18_0_,
orderhdrlo7_.address AS col_19_0_,
orderhdrlo7_.postal_code AS col_20_0_,
orderhdrlo7_.zone AS col_21_0_,
orderhdrlo7_.contact AS col_22_0_,
orderhdrlo7_.phone AS col_23_0_,
orderhdrlo7_.email AS col_24_0_,
orderhdrlo7_.op_date AS col_25_0_,
orderhdrlo7_.instruction AS col_26_0_,
orderhdr3_.dest_order_hdr_location_id AS col_27_0_,
orderhdrlo6_.unit_no AS col_28_0_,
orderhdrlo6_.name AS col_29_0_,
orderhdrlo6_.address AS col_30_0_,
orderhdrlo6_.postal_code AS col_31_0_,
orderhdrlo6_.zone AS col_32_0_,
orderhdrlo6_.contact AS col_33_0_,
orderhdrlo6_.phone AS col_34_0_,
orderhdrlo6_.email AS col_35_0_,
orderhdrlo6_.op_date AS col_36_0_,
orderhdrlo6_.instruction AS col_37_0_,
orderdet11_.product_code AS col_39_0_,
orderdet11_.product_desc AS col_40_0_,
orderdet11_.order_qty AS col_41_0_,
orderdet11_.serviced_qty AS col_42_0_,
orderdet11_.reason_code AS col_43_0_,
orderhdr3_.active_ind AS col_44_0_,
tripinfo4_.active_ind AS col_45_0_,
gnrlorg2_.active_ind AS col_46_0_,
gnrlcustom1_.active_ind AS col_47_0_,
commusersc0_.comm_user_id AS col_48_0_,
orderhdr3_.org_id AS col_49_0_,
orderhdr3_.customer_id AS col_50_0_,
orderhdrlo6_.op_date AS col_51_0_,
orderhdrlo6_.op_date AS col_52_0_,
orderhdr3_.id AS col_53_0_,
orderdet11_.order_hdr_id AS col_54_0_,
orderhdrlo6_.op_date AS col_55_0_,
tripinfo4_.job_no AS col_56_0_,
orderhdr3_.seq AS col_57_0_,
orderhdr3_.order_no AS col_58_0_
FROM comm_users_customers commusersc0_
JOIN gnrl_customer gnrlcustom1_ ON commusersc0_.gnrl_customer_id = gnrlcustom1_.id
JOIN gnrl_org gnrlorg2_ ON gnrlcustom1_.gnrl_org_id = gnrlorg2_.id
CROSS JOIN order_det orderdet11_
JOIN order_hdr orderhdr3_ ON gnrlcustom1_.id = orderhdr3_.customer_id
JOIN trip_info tripinfo4_ ON orderhdr3_.trip_info_id = tripinfo4_.id
JOIN service_type servicetyp5_ ON orderhdr3_.service_type_id = servicetyp5_.id
JOIN order_hdr_location orderhdrlo6_ ON orderhdr3_.dest_order_hdr_location_id = orderhdrlo6_.id
JOIN order_hdr_location orderhdrlo7_ ON orderhdr3_.source_order_hdr_location_id = orderhdrlo7_.id
JOIN order_hdr_location_time_windows timewindow8_ ON timewindow8_.order_hdr_location_id = orderhdr3_.dest_order_hdr_location_id
JOIN order_hdr_location orderhdrlo9_ ON timewindow8_.order_hdr_location_id = orderhdrlo9_.id;
In my code, I would like to filter using WHERE
SELECT * FROM myView view WHERE view.order_no = ?
but Java/PostgreSQL give error:
ERROR: column view.order_no does not exist
Please help as this is quite complicated as it involves multiple tables and a lot of columns. I am not sure why view.order_no does not exist because it is selected in col_5_0

You can reference the view by its name:
SELECT * FROM myView WHERE id = ?
Also view is a keyword in sql.

You have renamed the column order_no as col_5_0_. So you need to use that:
SELECT *
FROM myView v
WHERE v.col_5_0_ = ?;
That is, you can only reference the columns that are returned by the view.
Renaming columns to meaningless strings seems like a really bad idea -- at least if the views are exposed to human beings. It is not clear to me why anyone would want to obfuscate them.
Also, don't use view as a table alias (or any other identifier). It is a SQL keyword, and it is best to avoid those as identifiers.

Create your view like this way and use view reference in where clause
CREATE VIEW view_name 
AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
You can also filter rows during view creation.
SELECT *
FROM view_name
WHERE view_name.col_name = ?

Related

Ambigously defined column in a subquery

I've the following subquery in an sql query:
(
SELECT ID_PLAN, ID_CURSO, NEDICION, NOMBRE AS NOMBREUNIDAD FROM ASISTEN, ALUMNOS, UNIDADES
WHERE ASISTEN.COD = ALUMNOS.COD AND UNIDADES.IDESTRUCTURA = ALUMNOS.IDESTRUCTURA
AND UNIDADES.CDUNDORG = ALUMNOS.CDUNDORG
AND UPPER(TRANSLATE(UNIDADES.NOMBRE, 'áéíóúÁÉÍÓÚ', 'aeiouAEIOU')) LIKE '%CONSEJERIA%'
GROUP BY ID_PLAN, ID_CURSO, NEDICION) ASIS
Problem I have I believe lies in that both table ALUMNOS and UNIDADES have a column named 'NOMBRE' so if I attempt to execute the query I obtain:
00000 - "column ambiguously defined"
To avoid that I thought about changing NOMBRE AS NOMBREUNIDAD to:
UNIDADES.NOMBRE AS NOMBREUNIDAD
But if I do that I get a:
00000 - "not a GROUP BY expression"
So, I don't know what to do so that subquery executes properly.
What should I change to properly execute query without changing the column name?
Aliases are pretty useful, if you use them. The simplify queries and make them easier to read and maintain. I'd suggest you to do so, as it'll also help query to work because Oracle doesn't know which table you actually meant when you selected those 4 columns - which tables do they belong to?
This is just a guess as I don't know your tables so you'll have to fix it yourself. Also, I literally JOINed tables; try to avoid comma-separating them in FROM clause and doing join in WHERE clause as it is supposed to filter data.
GROUP BY, as already commented, is probably useless. If you wanted to fetch distinct set of values, then use appropriate keyword: distinct.
SELECT DISTINCT n.id_plan,
s.id_curso,
u.nedicion,
u.nombre
FROM asisten n
JOIN alumnos s ON n.cod = s.cod
JOIN unidades u
ON u.idestructura = s.idestructura
AND u.cdundorg = s.cdundorg
WHERE UPPER (TRANSLATE (u.nombre, 'áéíóúÁÉÍÓÚ', 'aeiouAEIOU')) LIKE '%CONSEJERIA%'
I managed to solve my problem:
(
SELECT ID_PLAN, ID_CURSO, NEDICION, UNIDADES.NOMBRE AS NOMBREUNIDAD
FROM ASISTEN, ALUMNOS, UNIDADES
WHERE ASISTEN.COD = ALUMNOS.COD AND UNIDADES.IDESTRUCTURA = ALUMNOS.IDESTRUCTURA
AND UNIDADES.CDUNDORG = ALUMNOS.CDUNDORG
AND UPPER(TRANSLATE(UNIDADES.NOMBRE, 'áéíóúÁÉÍÓÚ', 'aeiouAEIOU')) LIKE '%CONSEJERIA%'
GROUP BY UNIDADES.NOMBRE,ID_PLAN, ID_CURSO, NEDICION
)

How can I call view with specific where using SQL

I have view:
SELECT MIN(v.DOBA_VYSETRENI), v.ID_PACIENTA, v.ID_DOKTORA, d.MIN_DOBA
FROM vysetreni v,
doktor d
WHERE v.ID_DOKTORA = d.ID_DOKTORA
AND v.ID_VYSETRENI = 1
GROUP BY v.ID_DOKTORA, v.ID_PACIENTA, d.MIN_DOBA;
I can call view using:
select * from pohled;
It possible set some parameter (v.ID_VYSETRENI)?
Some like this:
select * from pohled WHERE v.ID_VYSETRENI = 2;
Thank you for your help
ID_VYSETRENI is not declared in your view specification, so add the field to the view specification, something like:
SELECT MIN(v.DOBA_VYSETRENI), v.ID_PACIENTA, v.ID_DOKTORA, d.MIN_DOBA, v.ID_VYSETRENI
FROM vysetreni v, doktor d
WHERE v.ID_DOKTORA = d.ID_DOKTORA
AND v.ID_VYSETRENI = 1
GROUP BY v.ID_DOKTORA, v.ID_PACIENTA, d.MIN_DOBA, v.ID_VYSETRENI;
And then you will be able to reference it when you query your view.
select * from pohled WHERE ID_VYSETRENI = 2;
Note that I included your field in your GROUP clause, however, as you may know already, could use MAX or MIN, you should know better the logic of your desired resulting data set to include the column, so I leave that to you.
And BTW OldProgrammer is right this should be tagged as SQL only.

Select all columns from one table and one from another where column equals variable

Sorry for the long title.
I have a statement which needs to grab all the columns from one row from BinConfig:
SELECT *
FROM BinConfig WITH(NOLOCK)
WHERE IssuerKey = #IssuerKey
But I also need to grab a single column from one row from CardRangeGroup also based on that IssuerKey column.
What I've tried:
SELECT
BinConfig.*, CardRangeGroup.Name
FROM
BinConfig
JOIN
CardRangeGroup WITH(NOLOCK)
WHERE
#IssuerKey = BinConfig.IssuerKey
AND #IssuerKey = CardRangeGroup.IssuerKey
Which gives me a syntax error near WHERE. I've tried to find resources online, but everywhere I look I can't find anything explaining how to select rows based on a passed in variable. Any help?
You need to specify how the tables should be joined. Try this:
SELECT BinConfig.*, CardRangeGroup.Name
FROM BinConfig
JOIN CardRangeGroup ON BinConfig.IssuerKey = CardRangeGroup.IssuerKey
WHERE #IssuerKey = CardRangeGroup.IssuerKey
The with(nolock) might not be needed (or a good idea) so I removed it.
try this , you don't need to use where
SELECT BinConfig.*, CardRangeGroup.Name FROM BinConfig JOIN
CardRangeGroup
ON CardRangeGroup.IssuerKey = BinConfig.IssuerKey AND #IssuerKey = CardRangeGroup.IssuerKey

In SQL , how do I JOIN a column that is usually null so that the data is still retrieved?

I want to incorporate a new column into a working SQL query.
However, it causes the whole query return nothing at all(because the column is mostly null in the database) .
Here's my pared-down code so far :
SELECT DISTINCT submittedRow.PERFORMED_DATE as "submitted",
supervisorRow.PERFORMED_DATE as "superv",
/* coalesce(sodRow.PERFORMED_DATE, TO_DATE('2000/07/07', 'YYYY/MM/DD') ) */ null AS "SOD"
hhs_umx_resp_activity submittedRow
join hhs_umx_resp_activity supervisorRow ON supervisorRow.reg_request_id = configRow.reg_request_id
/* join hhs_umx_resp_activity sodRow ON sodRow.reg_request_id = approvedRow.reg_request_id */
left join HHS_UMX_REG_REQUESTS hurr on hurr.reg_request_id = hur.reg_request_id
WHERE
and supervisorRow.ACTIVITY_RESULT_CODE = 'ASP'
AND submittedRow.activity_result_code = 'SBT'
/* AND sodRow.activity_result_code = 'ASD'*/
and hur.REG_REQUEST_ID IN ('262097')
The column that is mostly null, which I want to add in, is sodRow ( that's why the code AND sodRow.activity_result_code = 'ASD' is commented ).
Whenever I put back the extra join for sodRow , it just nulls out everything and I get no results at all. But I want it to work like a NVL or COALESCE, where it only displays that column if it exists, and otherwise just shows everything else.
I tried to create a view first in the code, then to do UNION on it. But it seems like view are only for PL/SQL code.
I also tried the outer joins, but this doesn't work.
I think the problem may be in the WHERE condition of my join code. I did like Dmitri suggest belwo :
AND nvl(sodRow.activity_result_code, 'ASD') = 'ASD'
AND nvl(configRow.activity_result_code, 'ACL') = 'ACL'
or also alternatively :
problem is that it won't return any rows. I.E If we're looking for 'ACL' then the previous check of 'ASD' becomes true and will render the next check useless.
I think I'm just having trouble visualizing how the joins work here
, thanks !
May be you can try left outer join
left outer join hhs_umx_resp_activity sodRow ON sodRow.reg_request_id = approvedRow.reg_request_id
and nvl
AND nvl(sodRow.activity_result_code, 'ASD') = 'ASD'
it will return records with null in sodRow.activity_result_code or 'ASD' in it

naming columns in excel with Complex sql

I’m trying to run this SQL using get external.
It works, but when I try to rename the sub-queries or anything for that matter it remove it.
I tried as, as and the name in '', as then the name in "",
and the same with space. What is the right way to do that?
Relevant SQL:
SELECT list_name, app_name,
(SELECT fname + ' ' + lname
FROM dbo.d_agent_define map
WHERE map.agent_id = tac.agent_id) as agent_login,
input, CONVERT(varchar,DATEADD(ss,TAC_BEG_tstamp,'01/01/1970'))
FROM dbo.maps_report_list list
JOIN dbo.report_tac_agent tac ON (tac.list_id = list.list_id)
WHERE input = 'SYS_ERR'
AND app_name = 'CHARLOTT'
AND convert(VARCHAR,DATEADD(ss,day_tstamp,'01/01/1970'),101) = '09/10/2008'
AND list_name LIKE 'NRBAD%'
ORDER BY agent_login,CONVERT(VARCHAR,DATEADD(ss,TAC_BEG_tstamp,'01/01/1970'))
You could get rid of your dbo.d_agent_define subquery and just add in a join to the agent define table.
Would this code work?
select list_name, app_name,
map.fname + ' ' + map.lname as agent_login,
input,
convert(varchar,dateadd(ss,TAC_BEG_tstamp,'01/01/1970')) as tac_seconds
from dbo.maps_report_list list
join dbo.report_tac_agent tac
on (tac.list_id = list.list_id)
join dbo.d_agent_define map
on (map.agent_id = tac.agent_id)
where input = 'SYS_ERR'
and app_name = 'CHARLOTT'
and convert(varchar,dateadd(ss,day_tstamp,'01/01/1970'),101) = '09/10/2008'
and list_name LIKE 'NRBAD%'
order by agent_login,convert(varchar,dateadd(ss,TAC_BEG_tstamp,'01/01/1970'))
Note that I named your dateadd column because it did not have a name. I also tried to keep your convention of how you do a join. There are a few things that I would do different with this query to make it more readable, but I only focused on getting rid of the subquery problem.
I did not do this, but I would recommend that you qualify all of your columns with the table from which you are getting them.
To remove the sub query in the SELECT statement I suggest the following:
SELECT list_name, app_name, map.fname + ' ' + map.lname as agent_login, input, convert(varchar,dateadd(ss, TAC_BEG_tstamp, '01/01/1970))
FROM dbo.maps_report_list inner join
(dbo.report_tac_agent as tac inner join dbo.d_agent_define as map ON (tac.agent_id=map.agent_id)) ON list.list_id = tac.list_id
WHERE input = 'SYS_ERR' and app_name = 'CHARLOTT' and convert(varchar,dateadd(ss,day_tstamp,'01/01/1970'),101) = '09/10/2008'
and list_name LIKE 'NRBAD%' order by agent_login,convert(varchar,dateadd(ss,TAC_BEG_tstamp,'01/01/1970'))
I used parentheses to create the inner join between dbo.report_tac_agent and dbo.d_agent_define first. This is now a set of join data.
The combination of those tables are then joined to your list table, which I am assuming is the driving table here. If I am understand what you are trying to do with your sub select, this should work for you.
As stated by the other poster you should use table names on your columns (e.g. map.fname), it just makes things easy to understand. I didn't in my example because I am note 100% sure which columns go with which tables. Please let me know if this doesn't do it for you and how the data it returns is wrong. That will make it easier to solve in needed.