FAQ Database Discussion Community


How to merge 2 SQL CASE statements for output in a single column

sql-server,merge,case
I'm using SQL Server 2014 and I have a query where I need to merge 2 CASE statements for output in a single column called, say, 'Market Final'. Case statement 1 is as follows: (CASE e.TravelAgencyTypeCode WHEN 'DMC' THEN g2.CountryGroup ELSE g.CountryGroup END) AS 'Market Final' When I run my...

Erlang : nested cases

if-statement,erlang,case
I'm very new to Erlang. I tried to find out if a list index is out of bounds (before trying it) so i wanted to do an if clause with something like if lists:flatlength(A) < DestinationIndex .... I discovered that those function results cannot be used in if guards so...

Can I use an array in a case statement?

c++,arrays,switch-statement,case
I would like to use an array of const int in a switch/case statement in C++. Is it possible? So far I've tried something like: int main() { int const tab[3] = {1,2,3}; int value(2); switch(value) { case tab[1]: cout << "result is: " << tab[0]<< endl; } return 0;...

Compare rows and calculate column of same row

sql,sql-server,select,case
If you see 2 Abc's then calculate with total like 9*2 = 18 and second row as 15*2 = 30 like that add Fun1 Fun2 Fun3 9 Abc Wxy Abc 15 def Abc Abc ...

onOptionsItemSelected is not functioning properly

java,android,android-actionbar,case
I have two buttons on my action bar, a logout button, and a create new message button. However, if i click the create new message button (where nothing is supposed to happen yet), it logs me back out. My code is set as what it is supposed to do. Any...

Switch case - unexpected behavior [duplicate]

c,switch-statement,case
This question already has an answer here: Switch statement not doing what I expect 4 answers I am working on a project en I tried to make the code more efficient but now there's an unexpected problem with my switch case that I can't seem to resolve. The code...

concatenated mysql query statement in a loop

php,mysql,foreach,case
I searched internet and stack-overflow for better logic I could work with but could not find. The error of the code is syntax error which I could not figure out. I am newbie and not well familiar with pdo or mysqli way. So I used deprecated mysql. As of now...

from keyword not found where expected in case statement

sql,case
I have one query which i written below. I am getting error. I have already added double quotes. Still not working. Please suggest me. SELECT TO_DATE(TO_CHAR(BATCH_CREATION_TIME,'YYYY/MM/DD'),'YYYY/MM/DD') AS CREATION_DATE, SUM(DECODE(CDR_ACTUAL_COUNT,NULL,0,CDR_ACTUAL_COUNT)) AS CCOLLECTED, SUM(DECODE(CDR_ACTUAL_COUNT,NULL,0,CDR_ACTUAL_COUNT)) - SUM(DECODE(CDR_PARSE_ERROR_COUNT,NULL,0,CDR_PARSE_ERROR_COUNT)) - SUM(DECODE(CDR_DISCARD_COUNT,NULL,0,CDR_DISCARD_COUNT)) AS COLLECTED,...

group_concat in mysql with “case when ” conditions

mysql,case,concat,group-concat,.when
I wrote sql code in mysql environment to concat the data . But, I couldn't get the correct result , and I am confusing about what is wrong with my sql code. my sql code is as follows: SELECT case when cc.complex_check_id = cmt.comp_o_id then cc.status cstatus,sgk.status sgstatus,cc.NAME complex_check_name,cc.min min_flag,cmt.comp_t_name...

Reduce lines, use case?

delphi,case
How to reduce the lines, I could use case? I feel that this code is too large, no way to improve? if valmes.Text = '01' then WebTesta.OleObject.Document.all.Item('expmonth', 0).value := '0'; if valmes.Text = '02' then WebTesta.OleObject.Document.all.Item('expmonth', 0).value := '1'; if valmes.Text = '03' then WebTesta.OleObject.Document.all.Item('expmonth', 0).value := '2'; if valmes.Text...

Android Multiple Intents - One Form

java,android,button,android-intent,case
Good afternoon, I am trying to create a basic menu in my andorid application which contains 5 buttons each bringing you to another form. I am trying to create the java to carry out this action but appear to be running into the following error with each of my buttons...

Querying the exact years in between two other dates (MS SQL)

sql-server-2008,case,datediff,datepart
I am struggling with an assignment and I am not sure if there is a solution. To be clear: I am not looking for the amount of years in between(datediff()). I have to join two tables: Table 1 with attributes: ID P_Startyear P_Endyear Table 2 with attributes: ID B_Year There...

MySQL SELECT Query: Add 28 days to the last date of a financial quarter

mysql,select,case
I am wanting to add 28 days to the last day of a quarter. I currently have the following to determine the Quarter period, how can I then add 28 days to the last date of the last month in the quarter. CASE -- Results: 2011-Q4 (Financial Year-Qtr) WHEN MONTH(T5.date_purchased)...

Joining tables and selecting foreign key where all rows meet condition in first table

mysql,sql,compare,case
I have 2 tables Accounts ID | Deleted? | Type 1 | 0 | Father 2 | 0 | Son 3 | 1 | Son 4 | 1 | Son 5 | 0 | Father 6 | 0 | Father 7 | 1 | Son 8 | 0 | Son...

verilog construct : expecting operand after case

case,verilog
Im currently doing a shift register for keypad (not sure if the term is correct though) the actual plan is when people press each numbered keypad, the value of corresponding keypad will be stored into a register. since user can only enter once at a clock cycle, shift register is...

MySQL Select when case

mysql,sql,database,case
i have those tables and i want to check the same attribute at the same time: Person id---name 1----Paul 2----Tom 3----Jim Age id---wert------personId 1----28--------1 2----25--------1 3----30--------3 i want to do something like this. select * from Person p, Age where personId = p.id and CASE WHEN name = 'Paul' THEN...

Using if-else condition inside a insert-select block

oracle,plsql,case,insert-select
I have two tables elig(mID, startDate, endDate) and claim(mID, serviceDate). I have to check if the serviceDate is between the startDate and endDate, and insert into a new table hasClaim(mID,startDate,endDate,Flag). The flag is to be set to 'Y' if the condition in satisfied and 'N' otherwise. What I have done...

T-SQL. CASE expression in WHERE clause using IN operator

sql,sql-server,tsql,case,where
If user put 800 as @WorkShop It should return all records having 800 workshop Id and 900 workshop id. If user pass any other Id as @WorkShop It should return only records for choosen @WorkShop Id. I have tried in following: SELECT * FROM Test WHERE Workshop IN ( CASE...

scrutinee is incompatible with pattern type; found : package.SomeObject required: Unit

scala,pattern-matching,sbt,case
I am trying a filesearcher program in scala. FileChecker.scala package fileSearcher import sun.org.mozilla.javascript.internal.ast.Yield class FilterChecker(filter:String) { def matches(content: String) = content contains filter def findMatchedFiles(fileObjects: List[IOObject]) = for(fileObject <- fileObjects if(fileObject.isInstanceOf[FileObject]) if(matches(fileObject.name))) yield fileObject } object FilterChecker{ def apply(filter: String)=new FilterChecker(filter) } IOObject.scala package fileSearcher import java.io.File trait...

Combining INSERT statements in a data-modifying CTE with a CASE expression

sql,postgresql,case,common-table-expression,sql-insert
My question is some kind of extension to Erwin Brandstetter's excellent answer in this thread on the correct use of WITH. My old query looks like this: WITH x AS ( INSERT INTO d (dm_id) SELECT dm_id FROM dm, import i WHERE dm.dm_name = i.dm_name RETURNING d_id ), y AS...

INNER JOIN with 2 CASE

mysql,select,case,inner-join
I try to do an INNER JOIN depending of the result of CASE. SELECT * FROM album INNER JOIN ( SELECT album_type CASE album.album_type WHEN 1 THEN "album_int" WHEN 2 THEN "album_ext" END FROM album) AS type ON type.album_id = album.id WHERE album.id = 6 LIMIT 1; I have see...

Bypass cases within a switch statement

java,switch-statement,case
I'm attempting to prevent additional cases within my switch statements from printing automatically when located below an initially satisfied case. Here is the code I'm building. I read previously that fallthrough is inevitable in switch statements(?) but I'm assuming there must be a way around this. System.out.println("\nQ1) What is the...

Oracle SQL CASE Including the expression clause Error ORA-00936: missing expression

sql,oracle,case
I have a CASE statement that works fine, and i want to include it in another CASE statement but i am getting a ORA-00936: missing expression error as i want it to use IN not =. Following this logic. The CASE statement can be used in Oracle/PLSQL. You could use...

Sum on case expression when working with dates

sql,sql-server,date,sum,case
I'm looking to create a view which will output the data in the following format AgedPeriod BillValue Status <1 35000 Outstanding 1-3 23386 Outstanding 3-6 5000 Outstanding I can use the code below to SUM each case statement into a new column and I could name the column headings after...

Can Oracle PL/SQL CASE statement include a SELECT query?

sql,oracle,plsql,case,plsqldeveloper
I'm trying to do something similar to this: CASE WHEN number IN (1,2,3) THEN 'Y' ELSE 'N' END; Instead I want to have a query in the place of the list, like so: CASE WHEN number IN (SELECT num_val FROM some_table) THEN 'Y' ELSE 'N' END; I can't seem to...

case statement inside where clause sql server

sql-server,case
I want to put a case condition inside where clause,ie if semester column of second table is null,i need to filter the columns where semester is null. If not,I need to filter the data on another condition. //if semester is null,I need the query to be like this: select *...

Defining a (scalar) function

sql-server,function,case
I cannot define a function like this, with case select: SELECT @NoShowRate=(Select case when tblPersonal.AnmeldungenXX = 0 and tblPersonal.Anmeldungen - tblPersonal.AnmeldungenNO = 0 then 0 when tblPersonal.Anmeldungen - tblPersonal.AnmeldungenNO > 0 and tblPersonal.Teilnahmen=0 then 0 when tblPersonal.Teilnahmen > tblPersonal.Anmeldungen then 100 else ((tblPersonal.Teilnahmen*100)/(tblPersonal.Anmeldungen - tblPersonal.AnmeldungenNO)) FROM dbo.tblPersonal WHERE tblPersonal.aktiv=1 and...

SQL Server : COUNT (DISTINCT (CASE) )

sql,sql-server,count,case,distinct
I need to count number of currencies and if there are more than two it need to be USD. It can be GBP, or anything else but if it's more than 1 then need to be USD. Well, my query should looks like this, but it didn't work: SELECT name,...

Bash Script: options - case: range of multiple numbers

linux,bash,case,command-line-arguments,optional-arguments
I'm working on a script in Linux Bash, with different kinds of options to use. Basically, the program is going to ping to the given ip-address. Now, I want to enable the user to write a range of ip-adresses in the terminal, which the program then will ping. Fe: bash...

Case statement to determine if I should union

sql-server,sql-server-2012,case,union
I currently want to do some sort of conditional union. Given the following example: SELECT age, name FROM users UNION SELECT 25 AS age, 'Betty' AS name Say I wanted to only union the second statement if the count of 'users' was >=2 , otherwise do not union the two....

can i do two times grouping in sql?

sql,group-by,case,add,mssql-jdbc
SELECT CASE WHEN "dbo"."ClaimDataFormat"."RELATION" = 'DAUGHTER' OR "dbo"."ClaimDataFormat"."RELATION" = 'SON' OR "dbo"."ClaimDataFormat"."RELATION" = 'SISTER' OR "dbo"."ClaimDataFormat"."RELATION" = 'FATHER' OR "dbo"."ClaimDataFormat"."RELATION" = 'MOTHER' OR "dbo"."ClaimDataFormat"."RELATION" = 'WIFE' OR "dbo"."ClaimDataFormat"."RELATION" = 'HUSBAND' THEN 'SPOUSE' ELSE 'SELF' END AS RELATION, sum("dbo"."ClaimDataFormat"."CLAIM_AMT") AS TOTAL_CLAIM_AMOUNT FROM "dbo"."ClaimDataFormat" GROUP BY "dbo"."ClaimDataFormat"."RELATION" The result...

How do I count distinct and total users and logins by date range across two tables?

sql,count,case,distinct
I am trying to count users created in a month, let’s say January 2015. Then I am trying to count users created as at January 31st, 2015. Then I am trying to count distinct user IDs that logged in during a month, which would also be January 2015. Then I...

Pascal case not working right

case,pascal
Ill be straight to it, how can I make this menu work right? When I run the program and want to select 1 the program just pauses and when I press a another button it just closes. How can I make the program to read(show whats in it) and use...

Expected primary expression before ')' token, switch-case

compiler-errors,switch-statement,case
This is an example of a switch case statement in a book I'm reading and I've had trouble with other examples too but I've been able to solve them by myself. I have no idea what I'm missing.I put a comment on the line I'm having trouble with, I keep...

SQL CASE LIKE with multiple choices

sql,sql-server,tsql,case,like
In my query I have following part of the code: CASE WHEN Field1 LIKE '%choice1%' OR Field1 LIKE '%Choice1%' .... THEN 'category 1' WHEN Field1 LIKE '%choicea%' OR Field1 LIKE '%Choiceb%' .... THEN 'category 2' END AS 'Cats' I have numerous of those choices (1line about 20), (2line about 15...

Python: How to test efficiency of IF statement to a Dictionary Case statement?

python,if-statement,case
I'd like to be able to test the efficiency of an IF statement to a dictionary case statement hack in Python. Since there is no case statement I am currently using the dictionary method. It looks like so.... self.options = {"0": self.racerOne, "1": self.racerTwo, "2": self.racerThree, "3": self.racerFour, "0f": self.racerFinish,...

mysql subquery as if condition ( only if needed )

mysql,if-statement,full-text-search,case
I want to perform a textsearch on a table containing posts belonging to topics within groups. Depending on the privacysettings for these groups I need to run a subquery to check if the requesting user is a member of the groups containg search matches. Databasescheme: Table: posts Columns: id, group_id,...

SQL - How to select from mulitple possible columns names?

sql,select,db2,case
I need to get data from several tables, but the last piece of data I need can come from one of three tables, and each table uses a unique column name. I've tried setting up a CASE statement in the select, but I've obviously made a syntax error. Am I...

SQL Output text or date depending on another field

sql,casting,case
I have a date field that sometimes I want to print a message instead of a date depending on the value in another field. I tried this: select CASE WHEN isExofficio = 1 THEN CAST ('Never Expires' as varchar(20)) ELSE boardDate END from tableName I know this won't work as...

aggregation condition in case when

mysql,sql,group-by,case,amazon-redshift
I have a dataset with a structure similar to the one bellow fruit, value apple, 234 apple, 2341 pear, 3233 grape, 323 pear, 3234 grap 1234 I am trying to find a count of a range of the numbers that are in the bottom 10% of the range by performing...

MySQL Query Case

mysql,case
This is my code, i have 2 columns - Modem = String, Total = Integer SELECT `Modem`, `Total`, CASE `Modem` WHEN 'Yes' THEN (`Total`+ 50) ELSE (`Total`+ 0) END AS ModemAndTotal FROM invoices I need when Modem = "Yes" add 50 to total (Total + 50)...

SQL: Combine Duplicate Rows And Case Statement Values in Final Data Output

sql,duplicates,subquery,case,distinct
I'm working on a SQL query that counts duplicate records that are based on a text field I am working with: where datasource = 'Web' or 'Internal'. I am currently using a case statement to count the number of times a record shows that value. My question is how do...

How to “sample” a value in VHDL?

case,vhdl,counter
So I have a modulo counter going from 1->15, then looping back around constantly in a seperate entity. I would like to, in a case statement depending on some outputs, sample this value on the rising_edge of a clock, but only do it once, otherwise the value will be constantly...

Pass returned list Erlang

case
I want to pass my returned list into case but I'm getting the "->" Error Here is my code: parse ( Element, [] ) -> false; parse(Element,N) -> re:split(N,"([*+])",[{return,list}]), parse ( Element, [ Item | ListTail ] ) -> case ( Item == Element ) of true -> true; false...

Transact-SQL local variable with case statement

sql,sql-server,tsql,variables,case
Given this simple example: DECLARE @aux INT SET @aux = NULL SELECT CASE WHEN @aux = NULL THEN 'null' ELSE 'not null' END AS ETest, CASE WHEN @aux <> NULL THEN 'not null' ELSE 'null' END AS ITest; I was expecting result : ETEST null, ITEST NULL, apparently this is...

SQL Server 2008 - update a field if date is older than 60 days

sql,.net,sql-server,case
I have three fields in my user_Group table: Banner_flag, warning_Date1 & warning_Date2 What i want to do is update warning_Date2 to today's date & also set banner_flag to = '2' if the date in warning_Date1 is over 60 days old and do nothing to those that don't meet this criteria....

T-SQL alternatives to nested CASE for better performance?

sql-server,tsql,nested,case,sql-tuning
I have a T-SQL query that is performing very poorly to the point that it times out. The culprits are these two nested CASE statements with embedded queries: SELECT CASE WHEN b.month_type = (CASE WHEN dbo.CURRENT_BUSINESSDAY(GETDATE()) >= 8 THEN 'Current Month BD2' ELSE (CASE WHEN dbo.CURRENT_BUSINESSDAY(GETDATE()) < 8 AND (SELECT...

Informix CASE and summing results

subquery,case,informix
I have finally joined after many month of always getting my answer from here without having to ask but rather simply searching on here :). I am fairly new to Informix and am struggling with my first CASE statement: The rough idea of it is that I am awarding points...

Defining Two Things per Case Statement Verilog

case,verilog
In my code, I am using a case statement to determine what seven seg LED digit is to turn on. I am also trying to use the same case statement to determine which actual number to show on that digit. My broken code: always @(*) begin case(sel_state) 2'b00: selector =...

How to put three conditions in CASE STATEMENT of SQL? [duplicate]

sql,case
This question already has an answer here: How do I do multiple CASE WHEN conditions using SQL Server 2008? 5 answers Here is my SQL Query: SELECT * ,CASE WHEN (ETA>10 OR Class='EOL') THEN 'Eligible' ELSE 'Not Applicable' END AS Eligible FROM XYZtable The result is: PN PD ETA...

using CASE to select column for SET in UPDATE statement IN SQL SERVER

sql,sql-server,sql-update,case
I want to execute the following statement. Is it possible to select which column to update using the CASE ? UPDATE TABVAR CASE WHEN M BETWEEN 0 AND 6 THEN SET M0_TO_6 = M WHEN M BETWEEN 7 AND 18 THEN SET M7_TO_18 = M WHEN M BETWEEN 19 AND...

Use Case: Almost same use case, different actors

uml,case,actor,extends,use
I have one use case "Transfer request" linked to two Actors (Analyst and Inspector). The scenario/exceptions/alternate flow are essentially the same, but for each actor the pre-conditions and post-conditions are different. The request has different states, and that final state and previous states differ depending on the actor that's calling...

Case Statement using || (OR)

ruby,hash,case
The following code I am trying to use to assign an email alias via an api to our ticketing system. @email.cc_list = case @site_id when /site1/ || /site2/; "smail-alias-1" when /site3/ || /site4/ || /site5/ || /site6/; "email-alias-2" when /site7/ || /site8/; "email-alias-3" when /site9/; "email-alias-4" when /site10/; "email-alias-5" end...

NESTED SELECT QUERY WITH CASE

sql,oracle,select,subquery,case
Please have a look at the query. The issue I am facing is this: The FROM_LOCATION,TO_LOCATION in THEN clause needs to be the value from B_TARIFFS, However when I prefix it with B_TARIFFS.FROM_LOCATION and B_TARIFFS.TO_LOCATION , I get an error that ORA-00904: Invalid identifier.. If it is available in ELSE...

SUM case returns value without GROUP BY

mysql,sql,group-by,sum,case
When I add SUM around my case select, it returns the summed value without the GROUP BY. The query I am using, without the SUM, is the following SELECT CASE WHEN subscription_types.type = 'Succes lidmaatschap' THEN 7 ELSE 8 END FROM subscription_used INNER JOIN training_sessions ON training_sessions.id = subscription_used.training_session_id INNER...

CASE Using CASE Statements to check for Null or Empty value

sql,oracle,case,concat
I need to write a DB function to concatenate 4 values. These values can be empty or null. How can I concatenate only the values that are not empty or null? Pseudo Code CASE WHEN #p1 IS NULL THEN '' ELSE #p1 END || CASE WHEN #p2 IS NULL THEN...

How to use CASE in JOIN statement to join two tables based on condition?

php,mysql,join,left-join,case
I have three tables : email, customer_new and customers_old. Now in email table there is a field called type that contains 0 or 1. So if type contains 0 then I want to fetch name column from customer_new table else from customer_old table. For this I made below mysql query...

Switch not entering cases but values match [closed]

c#,switch-statement,case
I have an issue with the code below. I have a switch statement that isn't entering any of its cases. Say the value of propType is "ID", the switch should match this to case "id" but it isn't doing so. What have I done wrong? case "button": Button ctrlButton =...

Need to write MySQL case statement

mysql,sql,case
I need to write a MySQL statement, but not sure how to write it using case statements. I would like to write something like this: select * from table where: if sign_off_1 is not null and sign_off_1 is not equal to 'Director' sign_off_1_status must be equal to Complete if sign_off_2...

scope of a variable in java in switch [duplicate]

java,switch-statement,case
This question already has an answer here: How does java scope declarations in switch case statements? 3 answers I am trying to understand how this is valid in case statement of a switch in Java. switch(someValue){ case abc: int i=0 break; case def: int i=0 // error because i...

PHP Loose comparison and null on Switch

php,null,switch-statement,comparison,case
Today I saw a strange bug on my code. I have a switch with comparison on case and if my variable equals null or '' it will always comes in the first case. My code : $sHost = filter_input(INPUT_SERVER, 'HTTP_HOST'); switch($sHost){ // Local case strpos($sHost, "dev.localhost") !== false: $this->_sEnv =...

Randomly generated values in CASE statements return NULL

sql-server,tsql,random,case
According to this post, the correct way of generating a random value in SQL Server is: ABS(CHECKSUM(NewId())) % 14 -- Returns a value between 0 and 13 However, when using this expression in a case statement, such as: SELECT CASE ABS(CHECKSUM(NEWID())) % 4 WHEN 0 THEN 'String A' WHEN 1...

comprare aggregate sum function to number in postgres

postgresql,sum,case
I have the next query which does not work: UPDATE item SET popularity= (CASE WHEN (select SUM(io.quantity) from item i NATURAL JOIN itemorder io GROUP BY io.item_id) > 3 THEN TRUE ELSE FALSE END); Here I want to compare each line of inner SELECT SUM value with 3 and update...

ORDER BY and CASE

sql-server,sql-order-by,case
I have the following script in SQL: ALTER PROC [dbo].[getRequests] @SortBy VARCHAR(50) = 'Date' AS SELECT [ReqDate], [RequestorOrg], [RequestCategory], [ReqDescription], [OrgCountVote] ORDER BY CASE WHEN @SortBy = 'Date (oldest first)' THEN [ReqDate] END ASC, [OrgCountVote] DESC, CASE WHEN @SortBy = 'Date (newest first)' THEN [ReqDate] END DESC, [OrgCountVote] , CASE...

Shorter CASE ISNULL(qry, '')='' THEN 'no' ELSE 'yes' END

sql,sql-server,case,isnull
Is there a shorter/better way to write this SQL statement? Edit: the inner sql select statement is a placeholder, the actual statement is more complex. SELECT CASE WHEN ISNULL((SELECT TOP 1 x FROM y), '') = '' THEN 'No' ELSE 'Yes' END AS BooleanValue It feels very kludgey because it...

Scala first program issue

scala,recursion,case,frequency
I have just started to learn Scala after some experience with functional programming in other languages. def freq(c:Char, y:String, list:List[(Char,Int)]): List[(Char,Int)] = list match{ case _ => freq(c, y.filter(_ == c), list :: List((count(c,y),c))) case nil => list } In the above code I am getting an error when trying...

MySQL CASE for value range doesn't work but nested IF's do?

mysql,range,decimal,case,nested-if
I'm probably missing something that is really, really simple, but I can't for the life of me figure out what it is that I'm not doing correctly... I have this query which is used to pull out hours people have completed in volunteering and then assign them an award based...

SQL Case Value Switching

sql,select,case
I am passing a series of double values in from another table ranging from -1 to 1. If the value is positive, I want to make it the difference between it and 1 (ie. 0.2 would then become .8). If value is negative, I want it to be the delta...

SQL bypass REPLACE by CASE statement

sql-server,tsql,replace,case,sql-server-2014
I have data where some records contain blank rows (=no space, no NULL). E.g.: LOCALE en-es en-uk uk-uk When I want to select that blank row, it's easy with: SELECT LOCALE FROM ABC WHERE LOCALE = '' But when I try to replace it as follows, it does not work,...

SQL UPDATE using CASE WHEN with PHP variable as argument

php,sql,case
I have a database storing materials in their respective formats, i.e. The Idiot (novel), Hamlet (play), Star Wars (screenplay), etc. I'm using a PHP function that removes articles (i.e. The/A/An/', etc.) and creates a variable ($mat_alph, assigned NULL if non-existent) by which it can later be alphabetised. This is only...

Time slots using Case in MySql

mysql,sql,case
I'm trying to sum on fields by 3 time slots with this code: SELECT CASE when TIME(v.time) between cast('00:00:00' as time) and cast('06:00:00' as time) then '00:00:00 - 06:00:00' when TIME(v.time) between cast('06:00:00' as time) and cast('16:00:00' as time) then '06:00:00 - 16:00:00' when TIME(v.time) between cast('16:00:00' as time) and...

T-SQL CASE Check for youngest date and then against the other values

sql-server,sql-server-2008,tsql,datetime,case
EDIT: Remade the whole question. Brought it the wrong way the first time. The Results should be like: MachineName | OrderNo | TaskID | Code | NettoProd | BrutoProd | DiffProd ========================================================================= F1 123456 101 O 100000 125000 25000 F1 123456 102 P8 1000000 1250000 250000 F1 123456 103 P1...

reversDigits is printing out base case input is not base case (java)

java,recursion,methods,case,base
The input for this method is "9876548" It returns 8 4 5 6 7 8 9 9876548 I don't want the "9876548" at the end. (Stack over flow format wont all Implement a recursive method printDigits that takes an integer num as a parameter and prints its digits in reverse...

SQL Server : conversion error numeric to varchar case

sql,sql-server,casting,case
I have this query: CASE ClaimsFees.TBA WHEN 0 THEN CAST(IndemnityReserve AS NUMERIC(9,2)) ELSE 'TBA' END AS 'Reserve Indemnity' but I always get this error: Error converting data type varchar to numeric I have tried to convert TBA as numeric but I can't do this, I also can't convert all the...

MySQL select specific value from duplicated rows

mysql,if-statement,case
I have table like this id name value 1 Leo 0 2 Ethan 0 3 Claire 0 4 Leo 1 5 Claire 1 6 Ethan 0 I would like to get results without duplicate name, if the value is 1, it should return the row with value 1, not the...

Dynamic SQL used in Case Statement in Stored Procedure

tsql,stored-procedures,case,dynamic-sql
I am developing a proof of concept application as requested by a client to act as a automation system that does an initial scrub of input data. One of the steps in this process is to look at a description field and determine how that maps to the clients provided...

Pass multiple value in where clause in SQL Server

sql,sql-server,case,multiple-columns,where-clause
SELECT "dbo"."ClaimDataFormat"."AGE", "dbo"."ClaimDataFormat"."RELATION", "dbo"."ClaimDataFormat"."NAME", "dbo"."ClaimDataFormat"."ENTRY_DATE", "dbo"."ClaimDataFormat"."CLAIM_AMT", CASE WHEN "dbo"."ClaimDataFormat"."Gender" = 'F' THEN 'FEMALE' ELSE 'MALE' END AS GENDER, "dbo"."ClaimDataFormat"."STATUS", "dbo"."ClaimDataFormat"."APPROVED_AMT" FROM "dbo"."ClaimDataFormat" WHERE "dbo"."ClaimDataFormat"."AGE" = CASE WHEN ${TimeGran} = '0-10' THEN 0 WHEN ${TimeGran} = '0-10' THEN 1 WHEN ${TimeGran} = '0-10' THEN 2 WHEN ${TimeGran} = '0-10' THEN 3...

Case statement in sqlserver in where clause with else as always true

mysql,sql,sql-server,tsql,case
I have used the always true statement e.g. 1 = 1 in case statement of where clause in MYSQL with following syntax: select * from tablename where (case when tablefield is not null then then tablefield = 'value' else 1 = 1 end) I want to know how can i...

Pandas function that iterates over values in a series with case statements

function,pandas,case,series
I have a dataframe that has contains a column of integers. I want to write a function that takes a series as an argument, iterates through each value of the series, and performs a case statement on each integer within the series, and returns a new series from the results...

Bash Case statement: check whether string ends in number

bash,scripting,numbers,case,ends
I'm writing a script and I'm kinda stuck at the following part: Inside a case statement, I want to check whether or not the "--sn" command is followed by a number (1-254). I thought i'd just use --sn*, but apperently * doesn't work for numbers? case "$1" in --sn* )...

Using a case statement to set the values of declared variables

sql,sql-server,database,tsql,case
I wanted to know if its possible to set the values of declared variables by using a case statement. example: CASE WHEN fieldValue ='stringValue1' THEN SET @DeclaredVar1 = 100 END ...

SQL loop through check

sql,sql-server,tsql,case
I'm having a slight issue creating an SQL query. I have a table with 4 columns 'Enquiry Date' , 'Taken Date' , 'Indication Date' , 'Cancelled Date' the table is called tbl_Sales. What i would like to do is create a bit a t-sql that says look at the 4...

Make if statement neater, unsure how to create a neat loop JAVA programming

java,loops,if-statement,case
@Override int getDiscountRate(float priceThisYear, float priceLastYear) { float totalPrice; totalPrice = priceThisYear + priceLastYear; if (totalPrice >= 250 && totalPrice < 350) { return 5; } else if (totalPrice >= 350 && totalPrice < 450) { return 6; } else if (totalPrice >= 450 && totalPrice < 550) {...

Case Statement in SQL Server

sql,sql-server,case
I am learning SQL case statements and have the following stored procedure. Select PT.[ID] 'TransactionID', PT.BatchNumber, PT.SequenceNumber, PT.TransactionDate, PT.TerminalID, PT.TotalAmount, PT.TransactionTypeID, TT.TransactionType, PT.PAN 'EmbossLine',PT.PreBalanceAmount, PT.PostBalanceAmount, RefTxnID, SettlementDate,PaidCash, CreditAmount, DiscountAmount, RefPAN, Remarks, PT.Product, case PT.Product when 1 then 'Taxi' end 'ProductName' case PT.Product when 2 then 'Airport Lounge' end 'ProductName' into...

Simple VBA Select Case statement not working, Why not?

vba,switch-statement,case
Simple Select Case statement is not working as expected. Message should show this as falling into the "too long" bucket but it comes up as "too short" Lenn = 20 Select Case Lenn Case 7 msg = "You've entered " & Lenn & " digits, this is ok" Case 11...

SQL Server query with case in select statement with multiple INNER JOINS

sql-server,tsql,select,case,inner-join
I have a query with returns a set of data about projects. The issue however is that some of the projects don't have a valid currency id. So i'm trying to build a query that will, if the currency id is 0, use the id 140 instead. This is what...

Why is this case when not working properly?

ruby,case
if ( item::class == RPG::Weapon ) print "yup" end case item::class when RPG::Item type = 0 when RPG::Weapon type = 1 when RPG::Armor type = 2 else type = 10 end I'm new to Ruby. The if statement runs fine and prints "yup", but the case statement isn't working...

Assigne a string to a variable in a case statement in the THEN clause

sql,sql-server,tsql,case
Here's what I have. I have tried quotes instead of =, I have removed the variable and tried just the select statement wrapped in quotes. Loosing my mind trying to figure this out. Yes, it is homework, I'm not asking for you to write it for me, just let me...

Cypher - atomic insert if node is absent

neo4j,match,case,cypher
I would like to write a single Cypher statement that tests for the existence of a path, adding it if the part is not present. Consider path (:A)-[:REL]->(:B{id:123}), then the existence of the path can be tested by OPTIONAL MATCH p = (:A)-[:REL]->(:B{id:123}) RETURN CASE COUNT(p) WHEN 0 THEN false...

Use A Sub-Query With A Case Statement

sql-server-2008,case
This may be impossible to achieve, and if so how would I re-write my query to still achieve the same results? I keep getting this error: Msg 130, Level 15, State 1, Line 2 Cannot perform an aggregate function on an expression containing an aggregate or a subquery. And this...

SQL: combine case and number to date conversion

sql,oracle,date,case
I want to do a sql statement which calculates in one table the substraction of 2 Date values. If the value is negative I just want to show it as the 0 value. The number value is the number of seconds a payment is in a current state. I convert...

Case statement query

sql,sql-server-2012,case
Can I use case statement on a field to change the value of another field? Something like that, SELECT TaskDescription, CASE When TaskDescription='Lab Dips / Handloom Sent' then seq ='1' When TaskDescription='Lab Dips / Handloom Approve' then seq ='2' end,seq FROM SomeTable I have some description of tasks in TaskDescription...

Insert.. select.. case - is there any way to get 2 columns?

tsql,insert,case
a have a table and i want to insert something to this table (very original of me ;P). so i have: INSERT into TARGET_TABLE ([...], tcol1, tcol2) SELECT [...], (SELECT CASE WHEN smth IS NOT NULL THEN SELECT Q_COL1 [...] WHEN smthelse IS NOT NULL THEN SELECT Q_COL1 [from the...

Case Sensitive matter in Java

java,case
I have a menu, with a "delete" option. That will delete from a list a town that the user introduced earlier. And I am asking you, is there any code that will ignore if the user will introduce upper case or lower case? For example, if my list has 3...

Case expressions and boolean

oracle,case
Please explain, why only the first one works and all the others return errors. returns 'blue': select case when 'a' = 'a' then 'blue' end from dual; Error: ORA-00920: invalid relational operator select case when true then 'blue' end from dual; ORA-00904: "TRUE": invalid identifier select case when 'a' =...

Assigning multiple results from CASE to WHERE col IN

sql-server,case
I get this message when using the case and i don't want to have an expression checking if the id is empty or not, that would be unnecessary extra code. Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >,...

SQL switch from decode to case

sql,oracle,oracle11g,case,h2
I have a query that does something like this... SELECT * FROM ... ... ORDER BY DECODE(APR(ACC.RATE,'X'), 'FIRST RATE', 1, 'SECOND RATE', 2, 3); Because I am dealing with h2 database and h2 doesnt have decode and decode alias is very difficult to implement so I was wondering if I...

Avoiding Divide By 0 Error With Multiple Case Statements

sql-server,case,divide-by-zero
The following is part of a SELECT clause that is giving me divide by 0 error: (SUM([Hours])/(SUM(CASE WHEN J.Description <> 'I' THEN 1 ELSE 0 END)) The following is how I am rectifying the denominator for the divide by 0 error: CASE WHEN(SUM(CASE WHEN J.Description <> 'I' THEN 1 ELSE...

MySQL Order By Case Casting Tinyint to String

mysql,sql-order-by,case
I have the following query: SELECT id, display_order FROM data_element_value WHERE key_id = 32 ORDER BY CASE WHEN (display_order IS NOT NULL) THEN display_order ELSE `value` END The expected output is : id display_order 1 1 13 2 15 3 16 10 But, I'm getting: id display_order 1 1 16...

NHibernate QueryOver CASE WHEN calculate on column value

select,nhibernate,case,queryover
I have been trying to do the following T-SQL in NHibernate QueryOver, but have not succeeded: SELECT Id, SUM(CASE MyValue WHEN 1 THEN Volume ELSE Volume * -1 END) FROM MyTable GROUP BY Id I am trying to sum up all Volume, but for MyValue=1 should be positive values otherwise...