Query SELECT calculated column with condition - sql

I need to create a column in my SELECT QUERY where it has a condition. Something like this:
SELECT NAME, ADDRESS, IF TABLE.COD=101 THEN return TABLE.VALUE AS TABLE
FROM CRM
So the third argument in the SELECT is my calculated column with a condition.
I believe this is simple but I am not being successful on solving this.

As you have not provided any data and expected output, It is really difficult to figure out what you exactly want. still you can try below one.
SELECT NAME, ADDRESS, (Case WHEN TABLE.COD=101 THEN TABLE.VALUE END) AS TABLE
FROM CRM

Another option would be using IIF function.
https://firebirdsql.org/refdocs/langrefupd20-iif.html
Frankly, the IIF is function only by name, by essence it is a shorthand, a macro substitution expanding into the CASE statement.
That close relationship probably was why you mistaken IF and CASE when writing your statement.
SELECT NAME, ADDRESS, IIF(TABLE.COD=101, TABLE.VALUE, NULL) as TABLE FROM CRM
Now, your statement seems not being real. You refer to the TABLE.COD and TABLE.VALUE - those are clearly some fields from some second table, but you forgot to include it in your FROM clause!
Because of that I think what you really may need is not some condition/calculation, but a plain old OUTER JOIN.
https://en.wikipedia.org/wiki/Join_(SQL)
SELECT A.NAME, A,ADDRESS, B.VALUE as TABLE
FROM CRM A
LEFT JOIN SomeTable B ON B.COD=101 AND B.XXXX = A.YYYY

Related

SQL GROUP BY 1 2 3 and SQL Order of Execution

This may be a dumb question but I am really confused. So according to the SQL Query Order of Execution, the GROUP BY clause will be executed before the SELECT clause. However it allows to do something like:
SELECT field_1, SUM(field_2) FROM myTable GROUP BY 1
My confusion is that if GROUP BY clause happens before SELECT, in this scenario I provided, how does SQL know what 1 is? It works with ORDER BY clause and it makes sense to me because ORDER BY clause happens after SELECT.
Can someone help me out? Thanks in advance!
https://www.periscopedata.com/blog/sql-query-order-of-operations
My understanding is because it's ordinal notation and for the SELECT statement to pass syntax validation you have to have at least selected a column. So the 1 is stating the first column in the select statement since it knows you have a column selected.
EDIT:
I see people saying you can't use ordinal notation and they are right if you're using SQL Server. You can use it in MySQL though.
select a,b,c from emp group by 1,2,3. First it will group by column a then b and c. It works based on the column after the select statement.
Each GROUP BY expression must contain at least one column that is not an outer reference. You cannot group by 1 if it is not a column in your table.

Is it possible to use column values to determine the tablename in a from clause of a subselect?

I would like to run a query that uses a column value (in which a tablename is stored) to determine the tablename in a from clause of a subselect.
Something like that:
SELECT column_with_tablename,
(SELECT COUNT(*) FROM VALUEOF(column_with_tablename)) as
numberofitems
FROM table1
I know that this is very fragile but i need it work.
(I inherited a database that stores tablenames in a column)
Is there a way ?
for a pure sql solution, refer to this answer
select column_with_tablename,
to_number(extractvalue(xmltype
(dbms_xmlgen.getxml('select count(*) c from '||column_with_tablename)
),'/ROWSET/ROW/C')) as count
from table1

Summarizing a table result in SQL

Given the below table as a SQL Result:
I want to use the above generated table and produce a table which clubs the given information into:
I have multiple areaName and multiple functionNames and multiple users. Please let me know if this is possible and how?
I have tried couple of things but I am just drained out now and need a direction. Any help is appreciated.
Even if you can provide a pseudo code, I can try and make use of it. Start from the SQL result as a given table.
Use correlated sub-queries to achieve the desired result. I've provided an example below. Test it for the first summary column, and then add in your other summary columns if it does. Hopefully this makes sense, and helps. Alternatively you could use a CTE (common table expression) to achieve similar results.
SELECT a.areaName, a.functionName
, (SELECT count(DISTINCT b.UserKey)
from AREAS b
where a.areaName = b.areaName
and a.functionName = b.functionName
and b.[1-add] = 1) as UsersinAdd
-- Lather/rinse/repeat for other summary columns
FROM AREAS a
group by a.areaName, a.functionName
Your problem stems from the de-normalised structure of your table. Columns [1-add],...,[8-correction] should be values in a column, not columns. This leads to more complex queries, as you have discovered.
The unpivot command allows you to correct this mistake.
select areaname, functionname, rights, count(distinct userkey)
from
(
select * from yourtable
unpivot (permission for rights in ([1-add], [2-update/display],[4-update/display all] , [8-correction] )) u
) v
group by areaname, functionname, rights

Can where clause condition be represented by another column

I have users enter the condistions for where clause for a table. Now I want to use that clause to do select. How can i do that? Example,
Condition table ( ckey, condition)
1 fn like 'G%' and ln like 'B%'
Name table (nkey, fn, ln)
Query wanted
select * from Name where ... use condition in row 1 of Condition table .....
Most DBMSes support a subquery inside WHERE, including correlated subquery.
It's hard to say without more info, but you'll probably need a (correlated?) subquery on Condition table.
One possible option would be to setup your condition table to mimic the table you're searching on. Then you could simply join the tables on all fields. In order for this to work you would have to default all columns in the condition table to '%' in case that condition isn't specified.
If your requirements are too complex for that to work, then another solution would be to use a stored procedure that generates dynamic sql based on what's in the condition table.
See below
accept myID prompt "Enter ID : "
SELECT * FROM myTable WHERE id='&myID'
OR
SELECT * FROM myTable WHERE id= #Enter_ID)
see which one is working with you...

What is the meaning of a constant in a SELECT query?

Considering the 2 below queries:
1)
USE AdventureWorks
GO
SELECT a.ProductID, a.ListPrice
FROM Production.Product a
WHERE EXISTS (SELECT 1 FROM Sales.SalesOrderDetail b
WHERE b.ProductID = a.ProductID)
2)
USE AdventureWorks
GO
SELECT a.ProductID, a.Name, b.SalesOrderID
FROM Production.Product a LEFT OUTER JOIN Sales.SalesOrderDetail b
ON a.ProductID = b.ProductID
ORDER BY 1
My only question is know what is the meaning of the number 1 in those queries? How about if I change them to 2 or something else?
Thanks for helping
In the first case it does not matter; you can select a 2 or anything, really, because it is an existence query. In general selecting a constant can be used for other things besides existence queries (it just drops the constant into a column in the result set), but existence queries are where you are most likely to encounter a constant.
For example, given a table called person containing three columns, id, firstname, lastname, and birthdate, you can write a query like this:
select firstname, 'YAY'
from person
where month(birthdate) = 6;
and this would return something like
name 'YAY'
---------------
Ani YAY
Sipho YAY
Hiro YAY
It's not useful, but it is possible. The idea is that in a select statement you select expressions, which can be not only column names but constants and function calls, too. A more likely case is:
select lastname||','||firstname, year(birthday)
from person;
Here the || is the string concatenation operator, and year is a function I made up.
The reason you sometimes see 1 in existence queries is this. Suppose you only wanted to know whether there was a person whose name started with 'H', but you didn't care who this person was. You can say
select id
from person
where lastname like 'H%';
but since we don't need the id, you can also say
select 1
from person
where lastname like 'H%';
because all you care about is whether or not you get a non-empty result set or not.
In the second case, the 1 is a column number; it means you want your results sorted by the value in the first column. Changing that to a 2 would order by the second column.
By the way, another place where constants are selected is when you are dumping from a relational database into a highly denormalized CSV file that you will be processing in NOSQL-like systems.
In the second case the 1 is not a literal at all. Rather, it is an ordinal number, indicating that the resultset should be sorted by its first column. If you changed the 1 to 4 the query would fail with an error because the resultset only has three columns.
BTW, the reason you use a constant like 1 instead of using an actual column is you avoid the I/O of actually getting the column value. This may improve performance.