Merging result from 2 columns with same name and not over-writing one - sql

I have a simple MySQL query like:
SELECT *
FROM `content_category` CC , `content_item` CI
WHERE CI.content_id = '" . (int)$contentId . "'
AND CI.category_id = CC.category_id
AND CI.active = 1
Both tables have a column called configuration one of which gets overwritten in the query i.e only content_item.configuration is returned in the result.
Short of implicitly naming and aliasing the columns like
SELECT CC.configuration as `category_configuration`,
CC.category_id as `.....
is there a way of selecting ALL data i.e * from both and resolve those duplicate column names in a non-destructive way.

You don't need to alias ALL the columns, just the one conflicting one:
SELECT *,CC.configuration as cc_conf, CI.configuration as ci_conf FROM `content_category` CC , `content_item` CI WHERE
CI.content_id = '" . (int)$contentId . "'
AND CI.category_id = CC.category_id
AND CI.active = 1

This demonstrates one of the many reasons why using the * wildcard is not a good practice all the time. All the columns are returned in the result set, but if you access them via an associative array or via object properites in your host language (e.g. PHP or Ruby) you can naturally only have one of the columns associated with each key or object property.
Solutions:
Fetch them all and reference the columns by ordinal position.
Stop using the wildcard for one table or the other, and give column aliases.
Rename your columns to be distinct.
Define a VIEW with the column aliasing spelled out, and query from the view.

Related

Select columns from a table with a space in its name

I'm trying to select columns from two tables, Lignes and Détail Production. Détail Production links to the first one with the key NoLigne (which is the same name in both tables).
I know that I have to put [ ] or `` around the table's name, but I'm having the error No value given for one or more required parameters, which I believe means that SQL doesn't recognize the name. I tried aliasing the name of the table having a space in its name, but I have the same error. Here is my code:
SELECT
NoProduction,
Quantite,
DateMaxProd,
Lignes.Référence
FROM
[Détail Production] AS D
INNER JOIN
Lignes ON D.NoLigne = Lignes.NoLigne
WHERE
D.Soldee = 0 AND
D.EtatLigne = 0 AND
Lignes.Soldee = 0 AND
(QteRecue - Quantite - Acompter * NbHS)>0
Unfortunately, I can't get rid of the alias or the name of the table in the FROM and WHERE clause because my tables share columns with the same name. I can't rename the tables or the columns, and I'm actually using the software Windev which uses HFSQL as a dbms. I'm trying to connect to an access database with the OLEDB connector, and when I switch to HFSQL it works.
Here is a mre:
SELECT
*
FROM
[Détail Production]
INNER JOIN
Lignes ON [Détail Production].NoLigne = Lignes.NoLigne
When using HFSQL database, it works, when using OLEDB with an access database, it throws the error No value given for one or more required parameter
Thanks for your help.
I found the problem:
SELECT
D.NoProduction,
D.Quantite,
D.DateMaxProd,
Lignes.Référence
FROM
[Détail Production] AS D
INNER JOIN
Lignes ON D.NoLigne = Lignes.NoLigne
WHERE
D.Soldee = 0 AND
D.EtatLigne = 0 AND
Lignes.Soldee = 0 AND
(D.QteRecue - D.Quantite - D.Acompter * D.NbHS) > 0
I was missing the comparison on the last condition of the WHERE clause. I thought it was because of the alias or the brackets because others online had similar problems and the error changed as I tried other ways of writing the FROM clause. The right way to write a name with spaces in HFSQL is with brackets [ ]. Also, there were problems with names not matching accents from the database.

How to write an Open SQL statement with substring in the JOIN ON condition? [duplicate]

I have the following select statement in ABAP:
SELECT munic~mandt VREFER BIS AB ZZELECDATE ZZCERTDATE CONSYEAR ZDIMO ZZONE_M ZZONE_T USAGE_M USAGE_T M2MC M2MT M2RET EXEMPTMCMT EXEMPRET CHARGEMCMT
INTO corresponding fields of table GT_INSTMUNIC_F
FROM ZCI00_INSTMUNIC AS MUNIC
INNER JOIN EVER AS EV on
MUNIC~POD = EV~VREFER(9).
"where EV~BSTATUS = '14' or EV~BSTATUS = '32'.
My problem with the above statement is that does not recognize the substring/offset operation on the 'ON' clause. If i remove the '(9) then
it recognizes the field, otherwise it gives error:
Field ev~refer is unknown. It is neither in one of the specified tables
nor defined by a "DATA" statement. I have also tried doing something similar in the 'Where' clause, receiving a similar error:
LOOP AT gt_instmunic.
clear wa_gt_instmunic_f.
wa_gt_instmunic_f-mandt = gt_instmunic-mandt.
wa_gt_instmunic_f-bis = gt_instmunic-bis.
wa_gt_instmunic_f-ab = gt_instmunic-ab.
wa_gt_instmunic_f-zzelecdate = gt_instmunic-zzelecdate.
wa_gt_instmunic_f-ZZCERTDATE = gt_instmunic-ZZCERTDATE.
wa_gt_instmunic_f-CONSYEAR = gt_instmunic-CONSYEAR.
wa_gt_instmunic_f-ZDIMO = gt_instmunic-ZDIMO.
wa_gt_instmunic_f-ZZONE_M = gt_instmunic-ZZONE_M.
wa_gt_instmunic_f-ZZONE_T = gt_instmunic-ZZONE_T.
wa_gt_instmunic_f-USAGE_M = gt_instmunic-USAGE_M.
wa_gt_instmunic_f-USAGE_T = gt_instmunic-USAGE_T.
temp_pod = gt_instmunic-pod.
SELECT vrefer
FROM ever
INTO wa_gt_instmunic_f-vrefer
WHERE ( vrefer(9) LIKE temp_pod ). " PROBLEM WITH SUBSTRING
"AND ( BSTATUS = '14' OR BSTATUS = '32' ).
ENDSELECT.
WRITE: / sy-dbcnt.
WRITE: / 'wa is: ', wa_gt_instmunic_f.
WRITE: / 'wa-ever is: ', wa_gt_instmunic_f-vrefer.
APPEND wa_gt_instmunic_f TO gt_instmunic_f.
WRITE: / wa_gt_instmunic_f-vrefer.
ENDLOOP.
itab_size = lines( gt_instmunic_f ).
WRITE: / 'Internal table populated with', itab_size, ' lines'.
The basic task i want to implement is to modify a specific field on one table,
pulling values from another. They have a common field ( pod = vrefer(9) ). Thanks in advance for your time.
If you are on a late enough NetWeaver version, it works on 7.51, you can use the OpenSQL function LEFT or SUBSTRING. Your query would look something like:
SELECT munic~mandt VREFER BIS AB ZZELECDATE ZZCERTDATE CONSYEAR ZDIMO ZZONE_M ZZONE_T USAGE_M USAGE_T M2MC M2MT M2RET EXEMPTMCMT EXEMPRET CHARGEMCMT
FROM ZCI00_INSTMUNIC AS MUNIC
INNER JOIN ever AS ev
ON MUNIC~POD EQ LEFT( EV~VREFER, 9 )
INTO corresponding fields of table GT_INSTMUNIC_F.
Note that the INTO clause needs to move to the end of the command as well.
field(9) is a subset operation that is processed by the ABAP environment and can not be translated into a database-level SQL statement (at least not at the moment, but I'd be surprised if it ever will be). Your best bet is either to select the datasets separately and merge them manually (if both are approximately equally large) or pre-select one and use a FAE/IN clause.
They have a common field ( pod = vrefer(9) )
This is a wrong assumption, because they both are not fields, but a field an other thing.
If you really need to do that task through SQL, I'll suggest you to check native SQL sentences like SUBSTRING and check if you can manage to use them within an EXEC_SQL or (better) the CL_SQL* classes.

Snowflake ignores statement in where clause where I'm comparing timestamps

so I'm building a SCD type 2 in snowflake, but it ignores the where clause in which is comparision between "to_timestamp" and "expiry_date". Expiry_date is a variable that is set to '9999-08-17 07:31:29.901000000' (as infinity) and To_timestamp is a column in table. I want to query only the rows that have to_timestamp set to infinity (they are still active) but snowflake seems to ignore this part of where clause. Below is some of the code (it should update the rows that are expired - that means change their "to_timestamp" to current time. and it does but it does to rows with timestamps of all kind - it ignores last line)
SET EXPIRY_DATE_NTZ = '9999-08-17 07:31:29.901000000';
SET CURRENT_DATE_NTZ = TO_TIMESTAMP_NTZ(CURRENT_TIMESTAMP());
UPDATE CUSTOMER_TARGET CT
SET CT.TO_TIMESTAMP = $CURRENT_DATE_NTZ
FROM POC.SNOWFLAKE_POC.CUSTOMER_STAGE CS
WHERE CT.C_CUSTOMER_ID = CS.C_CUSTOMER_ID
AND (CT.C_FIRST_NAME <> CS.C_FIRST_NAME OR CT.C_LAST_NAME <> CS.C_LAST_NAME OR CT.C_BIRTH_YEAR
<> CS.C_BIRTH_YEAR OR CT.C_BIRTH_COUNTRY <> CS.C_BIRTH_COUNTRY OR CT.C_LAST_REVIEW_DATE<>CS.C_LAST_REVIEW_DATE)
AND CT.TO_TIMESTAMP = $EXPIRY_DATE_NTZ;
I have two of these update statements (one for updates and one for deletes) and a merge statement for inserts. And it ignores the comparision in every single one, updating the rows that have "to_timestamp" set to something like "2021-08-24 07:11:53.510000000". I've tried every combination possible (between ... and ..., >= ... <=, <=, >=, comparing in "case" statement of update,...) - nothing. What could be the cause/solution?
As we do not know the structure of CUSTOMER_TARGET I would suggest to explicitly set the data type of EXPIRY_DATE_NTZ variable to match the column data type:
SET EXPIRY_DATE_NTZ = '9999-08-17 07:31:29.901000000';
SELECT $EXPIRY_DATE_NTZ;
DESCRIBE RESULT LAST_QUERY_ID();
to:
-- TIMESTAMP_NTZ as an example
SET EXPIRY_DATE_NTZ = '9999-08-17 07:31:29.901000000'::TIMESTAMP_NTZ;
SELECT $EXPIRY_DATE_NTZ;
DESCRIBE RESULT LAST_QUERY_ID();
By doing that way there are no "implicit conversions" involved in the process.
Another advice is usage of IS DISTINCT FROM instead of <>. IS DISTINCT FROM is NULL safe, which is important if columns are defined as nullable.
UPDATE CUSTOMER_TARGET CT
SET CT.TO_TIMESTAMP = $CURRENT_DATE_NTZ
FROM POC.SNOWFLAKE_POC.CUSTOMER_STAGE CS
WHERE CT.C_CUSTOMER_ID = CS.C_CUSTOMER_ID
AND (CT.C_FIRST_NAME IS DISTINCT FROM CS.C_FIRST_NAME
OR CT.C_LAST_NAME IS DISTINCT FROM CS.C_LAST_NAME
OR CT.C_BIRTH_YEAR IS DISTINCT FROM CS.C_BIRTH_YEAR
OR CT.C_BIRTH_COUNTRY IS DISTINCT FROM CS.C_BIRTH_COUNTRY
OR CT.C_LAST_REVIEW_DATE IS DISTINCT FROM CS.C_LAST_REVIEW_DATE)
AND CT.TO_TIMESTAMP = $EXPIRY_DATE_NTZ;
Your SQL does not have any issues with the filters (ORs are surrounded by the brackets etc). I assume that you have checked the execution profile, and did not see your filter (CT.TO_TIMESTAMP = '9999-08-17 07:31:29.901000000'). In this case, all rows in the target table should have this value in the column TO_TIMESTAMP.
I highly recommend you check the data first. If you are running multiple UPDATE/MERGE commands, you may miss that the data has already updated with this value.

Get all entries for a specific json tag only in postgresql

I have a database with a json field which has multiple parts including one called tags, there are other entries as below but I want to return only the fields with "{"tags":{"+good":true}}".
"{"tags":{"+good":true}}"
"{"has_temps":false,"tags":{"+good":true}}"
"{"tags":{"+good":true}}"
"{"has_temps":false,"too_long":true,"too_long_as_of":"2016-02-12T12:28:28.238+00:00","tags":{"+good":true}}"
I can get part of the way there with this statement in my where clause trips.metadata->'tags'->>'+good' = 'true' but that returns all instances where tags are good and true including all entries above. I want to return entries with the specific statement "{"tags":{"+good":true}}" only. So taking out the two entries that begin has_temps.
Any thoughts on how to do this?
With jsonb column the solution is obvious:
with trips(metadata) as (
values
('{"tags":{"+good":true}}'::jsonb),
('{"has_temps":false,"tags":{"+good":true}}'),
('{"tags":{"+good":true}}'),
('{"has_temps":false,"too_long":true,"too_long_as_of":"2016-02-12T12:28:28.238+00:00","tags":{"+good":true}}')
)
select *
from trips
where metadata = '{"tags":{"+good":true}}';
metadata
-------------------------
{"tags":{"+good":true}}
{"tags":{"+good":true}}
(2 rows)
If the column's type is json then you should cast it to jsonb:
...
where metadata::jsonb = '{"tags":{"+good":true}}';
If I get you right, you can check text value of the "tags" key, like here:
select true
where '{"has_temps":false,"too_long":true,"too_long_as_of":"2016-02-12T12:28:28.238+00:00","tags":{"+good":true}}'::json->>'tags'
= '{"+good":true}'

What to do with the error "Ambiguous Columns Defined"?

This is my sql command:
select INCOME_TYPE_ID,
REGION_CODE,
FIN_YEAR_CODE,
PORTION_AMOUNT
from INCOME.INCOME_TYPE,
COMMON.REGION,
INCOME.RECEIVE_DOC_PORTION,
INCOME.ASSESS_ORDER_ITEM,
ACCOUNTING.VOUCHER_ITEM_RECEIVE_DOC,
ACCOUNTING.VOUCHER_ITEM,
ACCOUNTING.VOUCHER,
ACCOUNTING.FIN_YEAR
where INCOME.RECEIVE_DOC_PORTION.ASSESS_ORDER_ITEM_ID = INCOME.ASSESS_ORDER_ITEM.ASSESS_ORDER_ITEM_ID
and INCOME.ASSESS_ORDER_ITEM.INCOME_TYPE_ID=INCOME.INCOME_TYPE.INCOME_TYPE_ID
and INCOME.RECEIVE_DOC_PORTION.RECEIVE_DOC_PORTION_ID = ACCOUNTING.VOUCHER_ITEM_RECEIVE_DOC.RECEIVE_DOC_PORTION_ID
and ACCOUNTING.VOUCHER_ITEM_RECEIVE_DOC.VOUCHER_ITEM_ID = ACCOUNTING.VOUCHER_ITEM.VOUCHER_ITEM_ID
and ACCOUNTING.VOUCHER_ITEM.VOUCHER_ID = ACCOUNTING.VOUCHER.VOUCHER_ID
and ACCOUNTING.VOUCHER.REGION_CODE = COMMON.REGION.REGION_CODE
and ACCOUNTING.VOUCHER.FIN_YEAR_CODE = ACCOUNTING.FIN_YEAR.FIN_YEAR_CODE
and I got this error:
Ambiguous Columns Defined
I'm Using SQL Developer as Oracle client.
Apparently one (or more) column names in your select list exists in more than one table of the FROM list.
You need to prefix every column in the SELECT list with the table it's coming from (it's also a good practice to always do that, regardless of the fact if they are ambigous)
Mention name of table before every column in select query.
Ambiguous column means that you have more than one column with the same name in one of the SELECT statements.
Try this instead, prefgixing all selected columns with their fully qualified names (as you have done elsewhere in your SELECT):
select INCOME.INCOME_TYPE.INCOME_TYPE_ID,
COMMON.REGION.REGION_CODE,
ACCOUNTING.FIN_YEAR.FIN_YEAR_CODE,
ACCOUNTING.VOUCHER_ITEM_RECEIVE_DOC.PORTION_AMOUNT
from INCOME.INCOME_TYPE,
COMMON.REGION,
INCOME.RECEIVE_DOC_PORTION,
INCOME.ASSESS_ORDER_ITEM,
ACCOUNTING.VOUCHER_ITEM_RECEIVE_DOC,
ACCOUNTING.VOUCHER_ITEM,
ACCOUNTING.VOUCHER,
ACCOUNTING.FIN_YEAR
where INCOME.RECEIVE_DOC_PORTION.ASSESS_ORDER_ITEM_ID = INCOME.ASSESS_ORDER_ITEM.ASSESS_ORDER_ITEM_ID
and INCOME.ASSESS_ORDER_ITEM.INCOME_TYPE_ID = INCOME.INCOME_TYPE.INCOME_TYPE_ID
and INCOME.RECEIVE_DOC_PORTION.RECEIVE_DOC_PORTION_ID = ACCOUNTING.VOUCHER_ITEM_RECEIVE_DOC.RECEIVE_DOC_PORTION_ID
and ACCOUNTING.VOUCHER_ITEM_RECEIVE_DOC.VOUCHER_ITEM_ID = ACCOUNTING.VOUCHER_ITEM.VOUCHER_ITEM_ID
and ACCOUNTING.VOUCHER_ITEM.VOUCHER_ID = ACCOUNTING.VOUCHER.VOUCHER_ID
and ACCOUNTING.VOUCHER.REGION_CODE = COMMON.REGION.REGION_CODE
and ACCOUNTING.VOUCHER.FIN_YEAR_CODE = ACCOUNTING.FIN_YEAR.FIN_YEAR_CODE
I had to guess the filly qualified name for
ACCOUNTING.VOUCHER_ITEM_RECEIVE_DOC.PORTION_AMOUNT
It might be
INCOME.RECEIVE_DOC_PORTION.PORTION_AMOUNT
But you should be able to resolve that easily.
Hope it helps...