How to change the value with a select in SQL? - sql

I need to have an other value instead of FULL and NONE but I must do it in the select.
SELECT Calendar_Month,Series,Cnt
FROM T_Cust_Eom_n
where TYP='REB'
and Series='FULL'
or TYP='REB'
and Series='NONE'
order by Series desc,Calendar_Month
Can I do this with an as anyhow?

Here is what you want:
SELECT Calendar_Month,
CASE WHEN Series = 'FULL'
THEN 'YOUR_TEXT_FOR_FULL'
WHEN Series = 'NONE'
THEN 'YOUR_TEXT_FOR_NONE'
END
AS Series
,Cnt
FROM T_Cust_Eom_n
WHERE (TYP='REB'and Series='FULL') OR (TYP='REB' and Series='NONE') ORDER BY Series DESC,Calendar_Month

Problem:
You should use () when you have multiple conditions in WHERE clause.
Solution:
Improved your query with IN. You can use any other values inside the ():
SELECT Calendar_Month,Series,Cnt
FROM T_Cust_Eom_n
where TYP='REB'
and Series IN ('FULL','NONE', 'ANOTHER_VALUE')
order by Series desc,Calendar_Month

Related

How to exclude SQL variable in output

I have a complex SQL query where I have a few cases that use END AS variableName. I then use variableName to do some logic and then create a new variable which I want in the output result. However when I run the query, all the END AS variableNames that I have used are also outputted in the results.
Is there a way that I can exclude these variables as I only want the final variable that uses these variableNames.
Thanks
EDIT, here is a query explaining my problem
SELECT DISTINCT
mt.src_id AS “SRC_ID”,
CASE
WHEN mt.cd = ‘TAN’ THEN
(
(
SELECT SUM(src_amt)
FROM source_table st
WHERE mt.id = st.id
AND st._cd = ‘TAN’
AND st.amt_cd = ‘ABL’)
)
END AS src_amt
FROM MAIN_TABLE mt
WHERE
mf.dt >= 2021-12-12
AND SRC_AMT > 10
I need SRC_AMT to be used as some sort of logic but when I run the query, it prints out in the output as it's own column. I want to ignore this variable
you can wrap the whole thing into a new select-statement:
select SRC_ID from ( <entire previous query here> )

PostgresSQL Cannot order by json_build_object result (got from subquery)

I have a SQL query. And I'd like to order by json field:
SELECT "ReviewPacksModel"."id",
(SELECT json_build_object(
'totalIssues', COUNT(*),
'openIssues', COUNT(*) filter (where "issues".status = 'Open'),
'fixedIssues', COUNT(*) filter (where "issues".status = 'Fixed')
)
FROM "development"."issues" "issues"
JOIN "development"."reviewTasks" as "rt" ON "issues"."reviewTaskId" = "rt".id
WHERE "issues"."isDeleted" = false
AND "rt"."reviewPackId" = "ReviewPacksModel"."id"
) as "issueStatistic"
FROM "development"."reviewPacks" AS "ReviewPacksModel"
WHERE "ReviewPacksModel"."projectId" = '2'
AND "ReviewPacksModel"."mode" IN ('Default', 'Live')
AND "ReviewPacksModel"."status" IN ('Draft', 'Active')
ORDER BY "issueStatistic"->'totalIssues'
LIMIT 50;
And I get an error:
ERROR: column "issueStatistic" does not exist
If I try to order by issueStatistic without ->'totalIssues', I will get another error:
ERROR: could not identify an equality operator for type json
It seems like I cannot extract field from the JSON.
I also tested it with this query:
SELECT "ReviewPacksModel".*,
(SELECT Count(*)
FROM "development"."issues" "issues"
JOIN "development"."reviewTasks" as "rt" ON "issues"."reviewTaskId" = "rt".id
WHERE "issues"."isDeleted" = false
AND "rt"."reviewPackId" = "ReviewPacksModel"."id"
) AS "issueStatistic"
FROM "development"."reviewPacks" AS "ReviewPacksModel"
WHERE "ReviewPacksModel"."projectId" = '2'
AND "ReviewPacksModel"."mode" IN ('Default', 'Live')
AND "ReviewPacksModel"."status" IN ('Draft', 'Active')
ORDER BY "issueStatistic"
LIMIT 50;
And it works without any problems. But I cannot use it cause it's not possible to return multiple columns from a subquery. I also tried to use alternatives like array_agg, json_agg, etc. but it doesn't help.
I know that it's possible to make multiple queries, but they aren't super fast and for me it's better to use json_build_object.
You can use aliases in ORDER BY, but you cannot use expressions involving aliases.
You'll have to use a subquery.
Also, you cannot order on a json. You'll have to convert it to a sortable data type. In the following I assume it is a number; you'll have to adapt the query if my assumption is wrong.
SELECT id, "issueStatistic"
FROM (SELECT "ReviewPacksModel"."id",
(SELECT json_build_object(
'totalIssues', COUNT(*),
'openIssues', COUNT(*) filter (where "issues".status = 'Open'),
'fixedIssues', COUNT(*) filter (where "issues".status = 'Fixed')
)
FROM "development"."issues" "issues"
JOIN "development"."reviewTasks" as "rt" ON "issues"."reviewTaskId" = "rt".id
WHERE "issues"."isDeleted" = false
AND "rt"."reviewPackId" = "ReviewPacksModel"."id"
) as "issueStatistic"
FROM "development"."reviewPacks" AS "ReviewPacksModel"
WHERE "ReviewPacksModel"."projectId" = '2'
AND "ReviewPacksModel"."mode" IN ('Default', 'Live')
AND "ReviewPacksModel"."status" IN ('Draft', 'Active')
) AS subq
ORDER BY CAST ("issueStatistic"->>'totalIssues' AS bigint)
LIMIT 50;
demos:db<>fiddle
You cannot order by type json because, simply spoken, there is no definition on how to handle different types included in the JSON object. But this gives you a type json:
"issueStatistic"->'totalIssues'
However, type jsonb can be ordered. So, instead of creating a type json object, you should use jsonb_build_object() to create a type jsonb object.
Alternatively you could cast your expression into type int (mind the ->> operator instead of your -> which casts the output into type text which can be directly cast into type int):
("issueStatistic"->>'totalIssues')::int
Edit:
As Laurenz mentioned correctly, to use aliases you need a separate subquery:
SELECT
*
FROM (
-- <your query minus ORDER clause>
) s
ORDER BY "issueStatistic"->'totalIssues'

OrientDB using LET values in subQuery

How can you use a LET temporary variable inside the Where clause in an OrientDB SQL subQuery.
Here is the context in wich I'm trying to use it.
select *, $t.d from Currency
let $t = (select createdDate.asLong() as d from 13:1)
where createdDate.asLong() >= $t.d and #rid <> #13:1
order by createdDate ASC
The validation in the where statement for the dates does not work. The subQuery actually works on its own. The Query works as well when replacing $t.d with the result from the subQuery.
The $t.d is an array so you are comparing something like createdDate.asLong() >= [1234599]
You have to do this: createdDate.asLong() >= $t[0].d

sql select with one value of two where

This is the only place that I get all answer ;)
I want to select :
SELECT
RTRIM(LTRIM(il.Num_bloc)) AS Bloc,
RTRIM(LTRIM(il.num_colis)) AS Colis,
cd.transporteur AS Coursier,
cd.origine AS Origine,
cd.destination AS Destinataire,
cd.adresse AS [Adresse Destinataire],
cd.poids AS Poids,
il.Signataire, il.num_cin AS CIN, il.date_livraison AS [Date Livraison]
FROM
dbo.cd
INNER JOIN
dbo.il ON cd.bloc = il.Num_bloc AND dbo.cd.colis = dbo.il.num_colis
WHERE
(il.Num_bloc = RTRIM(LTRIM(#ParamBloc)))
AND (il.num_colis = RTRIM(LTRIM(#ParamColis)))
In the way of getting result if the user put ether #ParamBloc or #ParamColis
Try using IsNull() function.
A simple query would go like this
Select * from yourTable
Where
Num_bloc = ISNULL(#ParamBloc, Num_block) AND
num_colis = ISNULL(#ParamColis, num_colis)
The second parameter would make the expression to true if the #parameter Bloc or Colis is null. This query would be useful for all 4 possible combination of these two parameter.

Issue with union query - select list not compatible

Been working on this query for some time now... Keep getting the error "Corrosponding select-list expressions are not compatible. I am selecting the same # of columns in each select statement.
create volatile table dt as (
SELECT
gcv.I_SYS_IDV,
gcv.i_pln,
gcv.c_typ_cov,
gcv.d_eff,
gcv.d_eff_pln,
gcv.c_sta,
gcv.d_sta,
gcv.c_mde_bft_fst,
gcv.a_bft_fst,
gcv.c_mde_bft_sec,
gcv.a_bft_sec,
gcv.c_mde_bft_trd,
gcv.a_bft_trd,
gcv.p_cre_hom,
gcv.c_cl_rsk,
gpv.c_val,
gpv.i_val,
gcv.c_pol,
gpv.i_prv
FROM Pearl_P.tltc906_gcv gcv,
pearl_p.tltc912_gpv gpv
WHERE gcv.i_pln > 0
AND gcv.i_pln = gpv.i_pln
and gpv.i_prv = '36'
and gcv.c_pol between 'lac100001' and 'lac100004'
UNION
SELECT
gcv.I_SYS_IDV,
gcv.i_pln,
gcv.c_typ_cov,
gcv.d_eff,
gcv.d_eff_pln,
gcv.c_sta,
gcv.d_sta,
gcv.c_mde_bft_fst,
gcv.a_bft_fst,
gcv.c_mde_bft_sec,
gcv.a_bft_sec,
gcv.c_mde_bft_trd,
gcv.a_bft_trd,
gcv.p_cre_hom,
gcv.c_cl_rsk,
gcv.c_pol,
gpv.i_val,
gpv.i_pln,
gpv.i_prv
FROM Pearl_P.tltc906_gcv gcv,
pearl_p.tltc912_gpv gpv
where NOT EXISTS(
SELECT 1
FROM pearl_p.tltc906_gcv gcv,
pearl_p.tltc912_gpv gpv
WHERE gcv.i_pln > 0
AND gcv.i_pln = gpv.i_pln
and gpv.i_prv = '36'
)
) with data
PRIMARY INDEX (i_sys_idv)
on commit preserve rows;
You should check the data types of each column. The data types must be compatible between each SELECT statement.
The last 4 values of your second select statement don't match the ones in your first statement. Try naming(using aliases) those columns the same thing(pairing them). To union you need to have the same columns between the sets.
Check out: http://msdn.microsoft.com/en-us/library/ms180026.aspx
The following are basic rules for combining the result sets of two
queries by using UNION:
The number and the order of the columns must be the same in all
queries.
The data types must be compatible.
Are the data types of each column the same in both portions of the query?
If the first character of the column name indicates the data type (i = integer, c = character, etc.) I'm guessing that the problem is with the second to last column in the select list. The first query is selecting gcv.c_pol, the second query is selecting gpv.i_pln.
Start commenting-out lines until it works. I.e., comment out all of the fields in each select list, and then one-by-one, un-comment the first one out, then the second, etc. You'll find it eventually.