Just wanted to see if there is a way to output a result that is not stored based on the addition of up to 4 fields?
Have a table that holds the count of passengers on a service for different categories, Adult, Child Infant and staff, and I want to try and out put a number based on the result of these fields that is not stored.
For example if the result of the add is >15 then output 45, if > 9 output 35. the output is the size of the coach that is required.
I know I can do it in Excel after the data is extracted but was wondering if it can be done before and included with the data?
Any suggestions and help appreciated.
Depending on what SQL program you're using, most offer the CASE WHEN statement (see this SQL Fiddle example)
CREATE TABLE CaseValues(
Value INT
)
INSERT INTO CaseValues
VALUES (1)
, (16)
, (9)
SELECT CASE WHEN Value > 15 THEN 45
WHEN Value BETWEEN 6 AND 14 THEN 35
ELSE 25 END AS Result
FROM CaseValues
You can also use CASE WHEN on multiple columns, see this example.
The Standard SQL CASE expression is the closest equivalent to the Excel IF(..) function:
SELECT
CASE WHEN Col1=Col2 THEN 'Foo'
WHEN Col1>Col2 THEN 'Bar'
WHEN Col3 Is NULL THEN Col4
ELSE 'unknown'
END As [CaseColumn]
FROM YourTable
You can do this with a query on the data:
select t.*,
(case when Adult + Child + Infant + staff > 15 then 45
when Adult + Child + Infant + staff > 9 then 35
end) as CoachSize
from t;
You can also do this using a view so it is available as if it were a table:
create view vw_t as
select t.*,
(case when Adult + Child + Infant + staff > 15 then 45
when Adult + Child + Infant + staff > 9 then 35
end) as CoachSize
from t;
And, in some databases, you can add a computed column directly into the table definition.
You can use a CASE statement. Here is the syntax.
SELECT
CASE WHEN DayOfBirth > 15
THEN 45
WHEN DayOfBirth > 9
THEN 35
ELSE
0
END
FROM BirthDaysTable
Related
This question already has answers here:
How to SUM two fields within an SQL query
(9 answers)
Closed 10 months ago.
My question is how can I select the currency not equal to USD and CNY and rename as others. Also, combining it into a new column AMT_Others.
ID Name Date AMT_HKD AMT_JPY AMT_USD AMT_TWD AMT_CNY
1 Amy 01/04/2022 0 5000 0 0 0
2 Bill 01/03/2022 200 0 0 0 0
3 Cathy 02/02/2022 0 0 80 2000 200
Result:
ID Name Date AMT_Others
1 Amy 01/04/2022 5000
2 Bill 01/03/2022 200
3 Cathy 02/02/2022 2000
my code: (It cannot generate what I want, what should be added? Thanks)
select ID, Name, Date, (AMT_HKD, AMT_JPY and AMT_TWD) as AMT_Others
basically add them up as long as we have only one non zero value for all currencies except USD and CNY
Select ID, Name, Date,
AMT_HKD + AMT_JPY + AMT_TWD as AMT_Others
from yourtable
You can get your desired result by using + instead of comma or AND:
SELECT id, name, ydate, amt_hkd + amt_jpy + amt_twd AS amt_others FROM yourtable;
But this is quite unpleasant in case there are null values in some of your columns. In this case, the sum would be null, too, even if some of the columns are not null. You can use COALESCE to prevent this and to force building a sum. Null values will be replaced by 0 (or another value if you change it):
SELECT id, name, ydate,
COALESCE(amt_hkd,0) + COALESCE(amt_jpy,0) + COALESCE(amt_twd,0) AS amt_others
FROM yourtable;
You can check this and see the difference between the two query results here: db<fiddle
You should also prevent table names or column names that are SQL key words, like the "date" column in your example. That'
s why I renamed it in my answer. Of course, if you can't change this, you have to live with it, but if you can, you should choose another name.
the other answers will work, unless there can be null values, if there is a row where one of these columns is ´null` then the result will also be null
select 1 + 2 -- output is 3
select 1 + 2 + null -- output is null
solution to this problem
isnull(AMT_HKD, 0) -- easy but slow
COALESCE(amt_hkd, 0) -- easy but still not the fastest solution
case when amt_hkd is null then 0 else amt_hkd end -- fastest
SELECT ID, Name, Date,
AMT_HKD + AMT_JPY + AMT_TWD as AMT_Others
FROM tb_name;
This will work
I have table with record_id and record_value. Query should return all id's and values but at the same time I need to return sum for specific group of id's. Here is example of my data:
record_id record_value
54 3
56 0
78 11
98 7
103 1
78 0
44 0
67 1
68 3
69 1
Query that I have returns rows with id's and values. I would like to get some of these columns as well in query result. Here is what I tried:
SELECT
record_id,
record_value
CASE
WHEN record_id IN ('54','56','67','68','69') THEN SUM(record_value)
ELSE ''
END AS RowSum
FROM Records
RowSum should return 19 but instead I'm getting an error:
SQL Error [257] [37000]: Implicit conversion from datatype 'VARCHAR' to 'NUMERIC' is not allowed. Use the CONVERT function to run this query.
I use Sybase database with DBeaver.
You can't use multiple results in one query. You can try with an UNION ALL
If you use CASE then both WHERE clauses should have the same type. You have used a NUMERIC (for SUM) an VARCHAR (for empty string ''). You need to unify them.
The code you might use is:
SELECT
record_id,
record_value,
FROM Records
union all
select null,
CASE
WHEN record_id IN ('54','56','67','68','69') THEN convert(varchar, SUM(record_value))
ELSE ''
END AS RowSum
I hope I'm not trying to do something that is not possible. ..
In my DB, the query below works and gets the values I want.
select LabelID, Amount
from tCASpreadsData
where LabelID in (3,4,5,7,9,10,11,12,16,17,18,19,21,22,23,24,28,29,30)
However, I don't want to build the list of LabelIDs manually each time. I also don't have a way to logically select them. So, I created a table with all the values listed in one field.
The query below finds the list I want in a field called SumA.
select SumA from tlCECLRatio where CATemplateID = 1 and LabelID = 148
(3,4,5,7,9,10,11,12,16,17,18,19,21,22,23,24,28,29,30)
However, when I combine the two queries, I get nothing.
SELECT LabelID, Amount
FROM tCASpreadsData
WHERE convert(nvarchar(255),LabelID) in
(Select SumA from tlCECLRatio where CATemplateID = 1 and LabelID = 148)
How can I use the value of SumA to create the 'in' list in my where clause?
you can try like below no need conversion
SELECT LabelID, Amount FROM tCASpreadsData where LabelID in
(
Select SumA from tlCECLRatio where CATemplateID = 1 and LabelID = 148
)
This will work:
select LabelID, Amount
from tCASpreadsData
where LabelID in (
select SumA
from tlCECLRatio
where CATemplateID = 1 and LabelID = 148
)
From your OP, it seems like you have the freedom to define the interim table (tlCECLRatio) however you like. So, I would like to suggest that you define it without a varchar field and instead use all integer fields. Here's how it would look with the values you have provided:
CATemplateID LabelID
1 3
1 4
1 5
1 7
1 9
1 10
1 11
1 12
1 16
1 17
1 18
1 19
1 21
1 22
1 23
1 24
1 28
1 29
1 30
If you need other collections of labels, you would give them a new template ID. Each collection is therefore defined by the value of CATemplateID.
To query the values you want, it's a simple join.
select SD.LabelID, SD.Amount
from tCASpreadsData SD inner join tlCECLRatio CR
on SD.LabelID = CR.LabelID
where CR.CATemplateID = 1
Side Note: I have been taught that the interim table also needs its own row ID, so I would probably define it as CECLRatioValue(RatioValueID, CATemplateID, LabelID) where RatioValueID is a sequence (or autonumber) value. But, that might be overkill for a simple cross-reference table. Just pointing out what has been recommended to me as good database practice.
Given table:
ID ANOTHERID ONE TWO THREE
X1 B1 15 15 -
X1 B2 10 - -
X2 B1 - 20 -
This query:
SELECT SUM (ONE + TWO + THREE) FROM (TABLE)
GROUP BY ID, ANOTHERID
I also tried
select sum(coalesce( ONE + TWO + THREE, ONE + TWO, ONE + THREE, ONE +
THREE))
at least one column has a null value. How can I still add them even if there is a null? As null and 0 have different meanings here (null means not started, 0 means not worked), I dont want to replace null with 0. Thanks
One method is:
SELECT SUM(COALESCE(ONE, 0) + COALESCE(TWO, 0) + COALESCE(THREE, 0))
FROM (TABLE)
GROUP BY ID, ANOTHERID;
Or, if you have at least one non-NULL value in each column:
SELECT SUM(ONE) + SUM(TWO) + SUM(THREE)
The time reporting table(s) should not allow null values, and the employee table should have a hire date field which can be used as criteria in your reporting queries. This will enable you to accurately report what management expects.
This solution worked for me
select
case when coalesce(sum(ONE), sum(TWO), sum(THREE)) is null then null else
sum(nvl(ONE,0) + nvl(TWO,0) + nvl(THREE,0)) end as
TOTALSUM
GROUP BY ID, ANOTHERID;
You might need to add another column in your table that describes the status of the employee (new, old) then make a condition like this:
if emp_status = 'new' then
--some code
working_hours := null;
else
--some code
working_hours : 0;
end if;
Table1
ID
12
21
12
21
...
Conditon
1)
I need to check either id should 12 or id should be 21. It should not be other numbers.
Below query is working
SELECT distinct ltrim(id) from table1 where ltrim(id) = '12' or ltrim(id) = '21')
2)
I dont need muliple number, always 12 or always 21, It should not be mixed, like
id
12
12
12
or
id
21
21
21
Below query is working
Declare #0_Recorddup int = 0
SELECT #0_Recorddup = Count(id) from (SELECT distinct id from table1) t1
if (#0_Recorddup = 0) or (#0_Recorddup > 1)
begin
''error message
end
How to merge a both query, can anyone help me....
ltrim(id) = '12'
You store id's - a numeric value - as a string? I am sorry, but I hope you program better.
For integers it is simple like in most other languages:
id = 12
and yes, etc. aredoable. I would suggest you grab some book about SQL and start learnng basics. Seriously.
I need to check either id should 12 or id should be 21. It should not be other numbers.
Simple. Trivial. Like in any other programming language:
id = 12 OR id = 21
alternative in SQL:
id IN (12, 21)
that is not as nice for 2 numbers but gets in handy fast.
"SQL for Dummies" (IBAM 1118607961, available through amazon etc.) is a decent book for someone at your level. Explains the basics. Like how not to compare numbers as strings.