Doubt in 'SELECT-CASE'
I have a doubt in 'SELECT-CASE'. There is this example of which i have :-
SELECT /*+ rule */ SUM(CASE WHEN age <= 15 THEN cnt ELSE 0 END) "upto 15 Years" ,
SUM(CASE WHEN age >= 16 AND age <= 20 THEN cnt ELSE 0 END) "16-20 Years" ,
SUM(CASE WHEN age >= 21 AND age <= 25 THEN cnt ELSE 0 END) "21-25 Years" ,
SUM(CASE WHEN age >= 26 AND age <= 30 THEN cnt ELSE 0 END) "26-30 Years" ,
SUM(CASE WHEN age >= 31 AND age <= 35 THEN cnt ELSE 0 END) "31-35 Years" ,
SUM(CASE WHEN age >= 36 AND age <= 40 THEN cnt ELSE 0 END) "36-40 Years" ,
SUM(CASE WHEN age >= 41 AND age <= 45 THEN cnt ELSE 0 END) "41-45 Years" ,
SUM(CASE WHEN age >= 46 AND age <= 50 THEN cnt ELSE 0 END) "46-50 Years" ,
SUM(CASE WHEN age >= 51 AND age <= 55 THEN cnt ELSE 0 END) "51-55 Years" ,
SUM(CASE WHEN age >= 56 AND age <= 60 THEN cnt ELSE 0 END) "56-60 Years" ,
SUM(CASE WHEN age >= 61 AND age <= 65 THEN cnt ELSE 0 END) "61-65 Years" ,
SUM(CASE WHEN age >= 66 AND age <= 70 THEN cnt ELSE 0 END) "66-70 Years" ,
SUM(CASE WHEN age > 70 THEN cnt ELSE 0 END) ">70 Years"
FROM
(SELECT /*+ rule */ROUND(MONTHS_BETWEEN(SYSDATE,ca.birthdate)/12) age,COUNT(1) cnt
FROM contract_all co , customer_all ca ,curr_co_status curr
WHERE ca.customer_id = co.customer_id
AND co.co_id = curr.co_id
AND curr.ch_status = 'a'
AND ca.birthdate IS NOT NULL
--AND co.co_activated BETWEEN '01-jan-2004' AND '31-dec-2004'
AND EXISTS ( SELECT 'x' FROM hss_cust_segment hcs
WHERE hcs.prgcode = ca.prgcode
AND hcs.description = 'POST')
GROUP BY ROUND(MONTHS_BETWEEN(SYSDATE,ca.birthdate)/12))
In this the statements on top like this-
SUM(CASE WHEN age >= 16 AND age <= 20 THEN cnt ELSE 0 END) "16-20 Years" ,
how does the increment happen in 'THEN cnt' because we are not doing the increment as such using '+1' kind of thing.
I hope, my question is clear. Please help in solving the doubt.
Regards.
Sample data, wrong output and desired output please...
I tried with this and it seems right...
WITH ca as (
select to_date('26-9-1990') birthdate from dual union all
select to_date('26-9-1989') birthdate from dual union all
select to_date('26-9-1974') birthdate from dual
SELECT /*+ rule */ SUM(CASE WHEN age <= 15 THEN cnt ELSE 0 END) "upto 15 Years" ,
SUM(CASE WHEN age >= 16 AND age <= 20 THEN cnt ELSE 0 END) "16-20 Years" ,
SUM(CASE WHEN age >= 21 AND age <= 25 THEN cnt ELSE 0 END) "21-25 Years" ,
SUM(CASE WHEN age >= 26 AND age <= 30 THEN cnt ELSE 0 END) "26-30 Years" ,
SUM(CASE WHEN age >= 31 AND age <= 35 THEN cnt ELSE 0 END) "31-35 Years" ,
SUM(CASE WHEN age >= 36 AND age <= 40 THEN cnt ELSE 0 END) "36-40 Years" ,
SUM(CASE WHEN age >= 41 AND age <= 45 THEN cnt ELSE 0 END) "41-45 Years" ,
SUM(CASE WHEN age >= 46 AND age <= 50 THEN cnt ELSE 0 END) "46-50 Years" ,
SUM(CASE WHEN age >= 51 AND age <= 55 THEN cnt ELSE 0 END) "51-55 Years" ,
SUM(CASE WHEN age >= 56 AND age <= 60 THEN cnt ELSE 0 END) "56-60 Years" ,
SUM(CASE WHEN age >= 61 AND age <= 65 THEN cnt ELSE 0 END) "61-65 Years" ,
SUM(CASE WHEN age >= 66 AND age <= 70 THEN cnt ELSE 0 END) "66-70 Years" ,
SUM(CASE WHEN age > 70 THEN cnt ELSE 0 END) ">70 Years"
FROM ( SELECT /*+ rule */ ROUND(MONTHS_BETWEEN(SYSDATE,ca.birthdate)/12) age, COUNT(1) cnt
FROM ca
GROUP BY ROUND(MONTHS_BETWEEN(SYSDATE,ca.birthdate)/12) )
upto 15 Years 16-20 Years 21-25 Years 26-30 Years 31-35 Years 36-40 Years 41-45 Years 46-50 Years 51-55 Years 56-60 Years 61-65 Years 66-70 Years >70 Years
0 2 0 0 1 0 0 0 0 0 0 0 0
1 rows selectedNH.
Similar Messages
-
I have not used queries which use 'SELECT-CASE' but i have seen a query like as below:-
SELECT /*+ rule */ SUM(CASE WHEN age <= 15 THEN cnt ELSE 0 END) "upto 15 Years" ,
SUM(CASE WHEN age >= 16 AND age <= 20 THEN cnt ELSE 0 END) "16-20 Years" ,
SUM(CASE WHEN age >= 21 AND age <= 25 THEN cnt ELSE 0 END) "21-25 Years" ,
SUM(CASE WHEN age >= 26 AND age <= 30 THEN cnt ELSE 0 END) "26-30 Years" ,
SUM(CASE WHEN age >= 31 AND age <= 35 THEN cnt ELSE 0 END) "31-35 Years" ,
SUM(CASE WHEN age >= 36 AND age <= 40 THEN cnt ELSE 0 END) "36-40 Years" ,
SUM(CASE WHEN age >= 41 AND age <= 45 THEN cnt ELSE 0 END) "41-45 Years" ,
SUM(CASE WHEN age >= 46 AND age <= 50 THEN cnt ELSE 0 END) "46-50 Years" ,
SUM(CASE WHEN age >= 51 AND age <= 55 THEN cnt ELSE 0 END) "51-55 Years" ,
SUM(CASE WHEN age >= 56 AND age <= 60 THEN cnt ELSE 0 END) "56-60 Years" ,
SUM(CASE WHEN age >= 61 AND age <= 65 THEN cnt ELSE 0 END) "61-65 Years" ,
SUM(CASE WHEN age >= 66 AND age <= 70 THEN cnt ELSE 0 END) "66-70 Years" ,
SUM(CASE WHEN age > 70 THEN cnt ELSE 0 END) ">70 Years"
FROM
(SELECT /*+ rule */ROUND(MONTHS_BETWEEN(SYSDATE,ca.birthdate)/12) age,COUNT(1) cnt
FROM contract_all co , customer_all ca ,curr_co_status curr
WHERE ca.customer_id = co.customer_id
AND co.co_id = curr.co_id
AND curr.ch_status = 'a'
AND ca.birthdate IS NOT NULL
--AND co.co_activated BETWEEN '01-jan-2004' AND '31-dec-2004'
AND EXISTS ( SELECT 'x' FROM hss_cust_segment hcs
WHERE hcs.prgcode = ca.prgcode
AND hcs.description = 'POST')
GROUP BY ROUND(MONTHS_BETWEEN(SYSDATE,ca.birthdate)/12))
Please tell a bit, how this works.
I hope, my question is clear. Please help in solving the doubt.
Regards.CASE statement works the same way as DECODE except that the later cannot use an operator. Think of CASE statement as having an IF...THEN...ELSE statement in you SELECT predicates.
-
Can anyone suggest a select case statement in place of my if statements?
I am having a little trouble switching my if statements to select case. Any help would be appreciated
Option Strict On
Option Explicit On
Public Class Form1
Private Player1 As String
Private Player2 As String
Private Player1Wins As Integer = 1
Private Player2Wins As Integer = 1
Private Tie As Integer = 1
' Close the program
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
' ask for players names
Private Sub frmMainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Player1 = InputBox("Enter Player 1's Name: ")
lblPlayer1.Text = (Player1 + "'s Score:")
Player2 = InputBox("Enter Player 2's Name:")
lblPlayer2.Text = (Player2 + "'s Score:")
End Sub
Private Sub btnRoll_Click(sender As Object, e As EventArgs) Handles btnRoll.Click
' game of rolling dice
Dim randGen As New Random
Dim intNum1 As Integer
Dim intNum2 As Integer
Dim intNum3 As Integer
Dim intNum4 As Integer
Dim intTotal As Integer
Dim intTotal2 As Integer
' make random integer from 1 through 6
intNum1 = randGen.Next(1, 7)
intNum2 = randGen.Next(1, 7)
intNum3 = randGen.Next(1, 7)
intNum4 = randGen.Next(1, 7)
' display the right image in picDie1
Select Case intNum1
Case 1
picDie1.Image = picOneDot.Image
Case 2
picDie1.Image = picTwoDots.Image
Case 3
picDie1.Image = picThreeDots.Image
Case 4
picDie1.Image = picFourDots.Image
Case 5
picDie1.Image = picFiveDots.Image
Case 6
picDie1.Image = picSixDots.Image
End Select
' display the right image in picDie2
Select Case intNum2
Case 1
picDie2.Image = picOneDot.Image
Case 2
picDie2.Image = picTwoDots.Image
Case 3
picDie2.Image = picThreeDots.Image
Case 4
picDie2.Image = picFourDots.Image
Case 5
picDie2.Image = picFiveDots.Image
Case 6
picDie2.Image = picSixDots.Image
End Select
' display the right image in picDie3
Select Case intNum3
Case 1
picDie3.Image = picOneDot.Image
Case 2
picDie3.Image = picTwoDots.Image
Case 3
picDie3.Image = picThreeDots.Image
Case 4
picDie3.Image = picFourDots.Image
Case 5
picDie3.Image = picFiveDots.Image
Case 6
picDie3.Image = picSixDots.Image
End Select
' display the right image in picDie4
Select Case intNum4
Case 1
picDie4.Image = picOneDot.Image
Case 2
picDie4.Image = picTwoDots.Image
Case 3
picDie4.Image = picThreeDots.Image
Case 4
picDie4.Image = picFourDots.Image
Case 5
picDie4.Image = picFiveDots.Image
Case 6
picDie4.Image = picSixDots.Image
End Select
' calculate and display total number of dots
intTotal = intNum1 + intNum2
lblTotal.Text = intTotal.ToString()
intTotal2 = intNum3 + intNum4
lblTotal2.Text = intTotal2.ToString()
' display the winner
If intTotal > intTotal2 Then
MessageBox.Show("Player1 Wins")
End If
If intTotal2 > intTotal Then
MessageBox.Show("Player2Wins")
End If
If intTotal = intTotal2 Then
MessageBox.Show("Tie")
End If
' display summary information when checkbox is checked
If CheckBox1.Checked = True And
intTotal > intTotal2 Then
lblWins.Text = CStr(Player1Wins)
Player1Wins = Player1Wins + 1
lblScores.Visible = True
End If
If CheckBox1.Checked = True And
intTotal2 > intTotal Then
lblWins2.Text = CStr(Player2Wins)
Player2Wins = Player2Wins + 1
lblScores.Visible = True
End If
If CheckBox1.Checked = True And
intTotal = intTotal2 Then
lblTies.Text = CStr(Tie)
Tie = Tie + 1
lblScores.Visible = True
End If
End Sub
End ClassPut everything into lists. Here is elementary sample to get you started.
Private lofDotImage As New List(Of Image)
Private randGen As New Random
Private picDie() As PictureBox
Private Sub setup()
ReDim picDie(3)
picDie(0).Location = New Point()
picDie(0).Size = New Size()
picDie(1).Location = New Point()
picDie(1).Size = New Size()
picDie(2).Location = New Point()
picDie(2).Size = New Size()
picDie(3).Location = New Point()
picDie(3).Size = New Size()
For _delta As Integer = 0 To 3
picDie(_delta).Visible = True
Me.controls.add(picDie(_delta))
Next _delta
Dim _dice1 As Image = Nothing
Dim _dice2 As Image = Nothing
Dim _dice3 As Image = Nothing
Dim _dice4 As Image = Nothing
Dim _dice5 As Image = Nothing
Dim _dice6 As Image = Nothing
lofDotImage.Add(_dice1)
lofDotImage.Add(_dice2)
lofDotImage.Add(_dice3)
lofDotImage.Add(_dice4)
lofDotImage.Add(_dice5)
lofDotImage.Add(_dice6)
End Sub
Private Sub roll()
Dim _lofRolls As New List(Of Integer)
Dim intScorePlayer1 As Integer = 0
Dim intScorePlayer2 As Integer = 0
For _delta As Integer = 0 To 3
_lofRolls.Add(randGen.Next(1, 7))
If _delta < 2 Then
intScorePlayer1 += _lofRolls(_delta)
Else
intScorePlayer2 += _lofRolls(_delta)
End If
picDie(_delta).Image = lofDotImage(_lofRolls(_delta))
Next _delta
If intScorePlayer1 = intScorePlayer2 Then
MessageBox.Show("Tie")
ElseIf intScorePlayer1 > intScorePlayer2 Then
MessageBox.Show("Player1 Wins")
Else
MessageBox.Show("Player2 Wins")
End If
End Sub
Edit: Also to get better random, seed the random once and generate many times, the more seed is the less random.
Also another tip: When comparing it is easy to check = and <> compared to < or > in my experience, also for only one possible outcome use one main if block instead of many. -
Using a scalar user defined function in a select case statement
I have a simple select statement below and I want to have a case statement for some conditions based on the result of the udf returned value. I then want the returned value from that specific case statement to be returned where i have indicated 'DISPLAY
ZIPCODE' below.
SELECT
CASE
WHEN (SELECT Top 1 ZipCode FROM ufn_GetAddressByBusinessEntityIDandAddressTypeID(table1.BusinessEntityID,712) IS NOT NULL THEN 'DISPLAY ZIPCODE'
WHEN (SELECT Top 1 ZipCode FROM ufn_GetAddressByBusinessEntityIDandAddressTypeID(table1.BusinessEntityID,714) as r) IS NOT NULL THEN 'DISPLAY ZIPCODE'
ELSE NULL
END as Zipcode,
FROM
table1SELECT COALESCE(ufn_GetAddressByBusinessEntityIDandAddressTypeID(table1.BusinessEntityID,712),ufn_GetAddressByBusinessEntityIDandAddressTypeID(table1.BusinessEntityID,712)) AS Zipcode
FROM table1
Nope. This is two function calls. coalesce(a, b, c, ...) is just syntatic sugar for
CASE WHEN a IS NOT NULL THEN a
WHEN b IS NOT NULL THEN b
WHEN c IS NOT NULL THEN c
END
But if you use isnull it's a different matter. (But isnull() permits two arguments.)
Erland Sommarskog, SQL Server MVP, [email protected] -
Hi i have a doubt in selection screen I had given statement as below now i can see the output screen and i'm getting the output also now i want to know the value of only one vendor. If i had given a vendor number it must select the particular data of that vendor only can u give me any suggestions please
SELECTION-SCREEN BEGIN OF BLOCK P WITH FRAME TITLE TEXT-000.
PARAMETERS: VENDORNO like EKKo-LIFNR,
PURORG like EKKO-EKORG,
PLANT like EKPO-WERKS,
PURDOC like EKKO-BEDAT.
SELECTION-SCREEN END OF BLOCK P.Hi Pavan,
<b>I think this is what u required when u select vendor number automatically for that particular vendor u require values in the remaining 3 parameter fields.
</b>
REPORT zex31 .
PARAMETERS: vendorno LIKE ekko-lifnr,
purorg LIKE ekko-ekorg,
plant LIKE ekpo-werks,
purdoc LIKE ekko-bedat.
DATA: dynfields TYPE TABLE OF dynpread WITH HEADER LINE.
DATA: return TYPE TABLE OF ddshretval WITH HEADER LINE.
AT SELECTION-SCREEN ON VALUE-REQUEST FOR vendorno.
CALL FUNCTION 'F4IF_FIELD_VALUE_REQUEST'
EXPORTING
tabname = 'EKKO'
fieldname = 'LIFNR'
dynpprog = sy-cprog
dynpnr = sy-dynnr
dynprofield = 'VENDORNO'
TABLES
return_tab = return
EXCEPTIONS
field_not_found = 1
no_help_for_field = 2
inconsistent_help = 3
no_values_found = 4
OTHERS = 5.
BREAK-POINT.
REFRESH dynfields.
READ TABLE return WITH KEY fieldname = 'VENDORNO'.
Add it back to the dynpro.
dynfields-fieldname = return-retfield.
dynfields-fieldvalue = return-fieldval.
APPEND dynfields.
Get the company code from db and add to dynpro
DATA: xekko TYPE ekko,
xekpo TYPE ekpo.
CLEAR xekko.
CLEAR xekpo.
SELECT SINGLE * INTO xekko
FROM ekko
WHERE lifnr = return-fieldval.
dynfields-fieldname = 'PURORG'.
dynfields-fieldvalue = xekko-ekorg.
APPEND dynfields.
dynfields-fieldname = 'PURDOC'.
dynfields-fieldvalue = xekko-bedat.
APPEND dynfields.
SELECT SINGLE * INTO xekpo
FROM ekpo
WHERE ebeln = xekko-ebeln.
dynfields-fieldname = 'PLANT'.
dynfields-fieldvalue = xekpo-werks.
APPEND dynfields.
Update the dynpro values.
CALL FUNCTION 'DYNP_VALUES_UPDATE'
EXPORTING
dyname = sy-cprog
dynumb = sy-dynnr
TABLES
dynpfields = dynfields
EXCEPTIONS
OTHERS = 8.
START-OF-SELECTION. -
Hai,
I have problem in my select query,
My previous select query:
SELECT rrcty
ryear
rbukrs
rzzpspid
SUM( hslvt )
SUM( hsl01 )
SUM( hsl02 )
SUM( hsl03 )
SUM( hsl04 )
SUM( hsl05 )
SUM( hsl06 )
SUM( hsl07 )
SUM( hsl08 )
SUM( hsl09 )
SUM( hsl10 )
SUM( hsl11 )
SUM( hsl12 )
SUM( mslvt )
SUM( msl01 )
SUM( msl02 )
SUM( msl03 )
SUM( msl04 )
SUM( msl05 )
SUM( msl06 )
SUM( msl07 )
SUM( msl08 )
SUM( msl09 )
SUM( msl10 )
SUM( msl11 )
SUM( msl12 )
FROM zzsl5t
INTO TABLE it_erbproj
WHERE rldnr EQ c_rldnr AND
rrcty EQ c_rrcty AND
ryear EQ v_srr_fyear AND
rbukrs EQ v_srr_ccode AND
racct EQ v_racct AND
rzzpspid IN r_zzpspid
GROUP BY RRCTY ryear RBUKRS rzzpspid.
now i want change the above select query as,
If user enters input period 03 means,
i have to select
SELECT rrcty
ryear
rbukrs
rzzpspid
SUM( hslvt )
SUM( hsl01 )
SUM( hsl02 )
SUM( hsl03 )
SUM( mslvt )
SUM( msl01 )
SUM( msl02 )
SUM( msl03 )
only, not to select all the periods.
how can i give fields dynamically.
please suggest me.
ElamaranDuplicate message. Please close this one and look at my answer Doubt in Select query.
-
I NEED TO KNOW HOW TO RUN IN PL THE STATEMENT select case
when ...
thanksHi
SELECT with a CASE statement will not work in 8i when using
static SQL. However if you are using dynamic SQL to execute it,
then it will be fine. This is because the dynamic SQL statement
is passed to the SQL engine for executing wheras static SQL is
compiled by the PL/SQL compiler, which does not understand the
complete SQL syntax.
This will be fixed in 9i as well as PL/SQL in 9i also includes
the CASE statement itself (outside of SQL).
Guido -
Hi all,
I've this problem: insert into Table_A some values from Table_B... with one derivated/calculated filed.
Example
INSERT INTO Table_A (id_part, vendtype, origin, proven, desc)
SELECT id_p, vendt, origin, proven, <calculate/derivated_field_desc>
FROM Table_BThe rules for calculate the field desc inserted on Table_A are 1. IF vendt='V' AND origin='N' AND proven!='04' THEN ---> desc='TRANSFER'
2. IF vendt='M' AND origin='N' AND proven!='04' THEN ---> desc='IMPORTED'
3. IF proven='04' THEN ---> desc='BAD'So what I use in <calculate/derivated_field_desc> on my INSERT INTO statement??
Can I use a SELECT CASE WHEN... or only DECODE is a right solution?
Edited by: trebbia on 15-nov-2010 12.51Ok,
I prefer use select case when... because trasform my rules in DECODE statement is more difficult
So I write: INSERT INTO Table_A (id_part, vendtype, origin, proven, desc)
SELECT id_p, vendt, origin, proven, SELECT CASE WHEN vendt='V' AND origin='N' AND proven!='04' THEN 'TRANSFER'
WHEN vendt='M' AND origin='N' AND proven!='04' THEN 'IMPORTED'
WHEN proven='04 THEN 'BAD'
END
FROM Table_BObtain this error:
40/56 PL/SQL: ORA-00936: missing expression
33/1 PL/SQL: SQL Statement ignored
PS: I use '<' '>' and not '!=' in my code... here not prompted correctly '<''>'
Edited by: trebbia on 15-nov-2010 13.04
Edited by: trebbia on 15-nov-2010 13.06 -
SELECT CASE WHEN not working?
Hello, can't figure out why the following statement continues to return NULL values and seems to not recognize my case when portion?...
INSERT tbl_Main
select OrderID
,(select
case
when (b.OrderValue is null or b.OrderValue = '') then 'Y'
else b.OrderValue
end
from tbl_OrderDetails b where b.OrderID = a.OrderID and b.DetailID = '7')
AS OrderStatus
from tbl_Order a
Thanks in advanced.Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. Temporal data should
use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect.
This is minimal polite behavior on SQL forums.
1. The use of the “tbl-” prefix is a design flaw called “tibbling” and people will laugh at you for it.
2. Do not nest selects inside a select list; the performance stinks.
3. Why do you think “A”, "D” etc are good aliases that will make maintaining this code easier? Noobs do this is match the names of tape drives on old hardware!
4. Why do you think that treating a NULL and an empty string as the same is a good idea? Use a CHECK (order_value <> '').
My guess is you could write this instead:
INSERT INTO Orders
SELECT order_id, COALESCE (D.order_value, 'Y') AS order_status
FROM Order_Details AS D
WHERE D.order_id = Orders.order_id
AND D.detail_id = '7')
AS order_status;
But this still smells bad. A status is a state of being so it has a temporal component. Order details do not usually have an id; the item identifier (EAN, UPC, SKU, or whatever) is used.
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL -
Hello experts.
i'm in sales offer > table OQUT.
It is possible to have a FMS that select a query depending the OQUT.cardcode??
E.G.
if cardcode is A then run query A
else cardcode is B then run query B
i try this query :
SELECT CASE $[OQUT.cardcode]
when '+MASTERFD' Then
select a.itemcode, a.price, c.itmsgrpnam
from
itm1 a
inner join oitm b on a.itemcode = b.itemcode
inner join oitb c on b.itmsgrpcod = c.itmsgrpcod
where
a.pricelist = (select listnum from ocrd where cardcode = $[OQUT.CardCode]) and
c.itmsgrpnam = $[OQUT.U_JDT_OFF_MER] and
(a.price <> 0 and a.price is not null)
for browse
else
select a.itemcode, c.itemname, a.price, a.fromdate, a.todate, d.itmsgrpnam, a.linenum
from spp1 a inner join
(select cardcode, itemcode, max(todate) as ultimo from spp1 group by cardcode, itemcode) b
on a.cardcode = b.cardcode and a.itemcode = b.itemcode and a.todate = b.ultimo
inner join oitm c on a.itemcode = c.itemcode
inner join oitb d on c.itmsgrpcod = d.itmsgrpcod
where a.cardcode = $[$4.0]
end
Than's in advence...
And sorry for my english....Hi Istvan...
The query run in this mode:
If $[OQUT.cardcode]='+MASTERFD'
select a.itemcode, a.price, c.itmsgrpnam
from
itm1 a
inner join oitm b on a.itemcode = b.itemcode
inner join oitb c on b.itmsgrpcod = c.itmsgrpcod
where
a.pricelist = (select listnum from ocrd where cardcode = $[OQUT.CardCode]) and
c.itmsgrpnam = $[OQUT.U_JDT_OFF_MER] and
(a.price != 0 and a.price is not null)
else
select a.itemcode, c.itemname, a.price, a.fromdate, a.todate, d.itmsgrpnam, a.linenum
from spp1 a inner join
(select cardcode, itemcode, max(todate) as ultimo from spp1 group by cardcode, itemcode) b
on a.cardcode = b.cardcode and a.itemcode = b.itemcode and a.todate = b.ultimo
inner join oitm c on a.itemcode = c.itemcode
inner join oitb d on c.itmsgrpcod = d.itmsgrpcod
where a.cardcode = $[OQUT.cardcode]]
Thank you a lot... -
May you check this simple select case...
Guys, please, can you check this stupid code? I'm totally shattered and maybe I don't see the simple thing...
with cte as (
SELECT CORE FROM IMPORTOIL group by core)
,cte2 as
(select core , mps, technology
from cte xx right join GeneratorTypo gt on xx.core=gt.mps)
select core, mps, technology , case core when null then 'Import ' else technology end from cte2
even if I got several core NULL it retrieve for the select case only the technology and never the 'Import'. Pratically, if ( I miss 2012 wit the simple iif) the core is null write the same value that there is in technology otherwise write 'Import'...what's
wrong with that?Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. Nothing here is correct!
Temporal data should use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect.
This is minimal polite behavior on SQL forums. You also need to learn the syntax for a CASE expression:
CASE WHEN core IS NULL THEN 'IMPORT ' ELSE technology END
The CASE expression is an *expression* and not a control statement; that is, it returns a value of one data type. SQL-92 stole the idea and the syntax from the ADA programming language. Here is the BNF for a <case specification>:
<case specification> ::= <simple case> | <searched case>
<simple case> ::=
CASE <case operand>
<simple when clause>...
[<else clause>]
END
<searched case> ::=
CASE
<searched when clause>...
[<else clause>]
END
<simple when clause> ::= WHEN <when operand> THEN <result>
<searched when clause> ::= WHEN <search condition> THEN <result>
<else clause> ::= ELSE <result>
<case operand> ::= <value expression>
<when operand> ::= <value expression>
<result> ::= <result expression> | NULL
<result expression> ::= <value expression>
The searched CASE expression is probably the most used version of the expression. The WHEN ... THEN ... clauses are executed in left to right order. The first WHEN clause that tests TRUE returns the value given in its THEN clause. And, yes, you can nest CASE
expressions inside each other. If no explicit ELSE clause is given for the CASE expression, then the database will insert a default ELSE NULL clause. If you want to return a NULL in a THEN clause, then you must use a CAST (NULL AS <data type>) expression.
I recommend always giving the ELSE clause, so that you can change it later when you find something explicit to return.
The <simple case expression> is defined as a searched CASE expression in which all the WHEN clauses are made into equality comparisons against the <case operand>. For example
CASE iso_sex_code
WHEN 0 THEN 'Unknown'
WHEN 1 THEN 'Male'
WHEN 2 THEN 'Female'
WHEN 9 THEN 'N/A'
ELSE NULL END
could also be written as:
CASE
WHEN iso_sex_code = 0 THEN 'Unknown'
WHEN iso_sex_code = 1 THEN 'Male'
WHEN iso_sex_code = 2 THEN 'Female'
WHEN iso_sex_code = 9 THEN 'N/A'
ELSE NULL END
There is a gimmick in this definition, however. The expression
CASE foo
WHEN 1 THEN 'bar'
WHEN NULL THEN 'no bar'
END
becomes
CASE WHEN foo = 1 THEN 'bar'
WHEN foo = NULL THEN 'no_bar' -- error!
ELSE NULL END
The second WHEN clause is always UNKNOWN.
The SQL-92 Standard defines other functions in terms of the CASE expression, which makes the language a bit more compact and easier to implement. For example, the COALESCE () function can be defined for one or two expressions by
1) COALESCE (<value exp #1>) is equivalent to (<value exp #1>)
2) COALESCE (<value exp #1>, <value exp #2>) is equivalent to
CASE WHEN <value exp #1> IS NOT NULL
THEN <value exp #1>
ELSE <value exp #2> END
then we can recursively define it for (n) expressions, where (n >= 3), in the list by
COALESCE (<value exp #1>, <value exp #2>, . . ., n), as equivalent to:
CASE WHEN <value exp #1> IS NOT NULL
THEN <value exp #1>
ELSE COALESCE (<value exp #2>, . . ., n)
END
Likewise, NULLIF (<value exp #1>, <value exp #2>) is equivalent to:
CASE WHEN <value exp #1> = <value exp #2>
THEN NULL
ELSE <value exp #1> END
It is important to be sure that you have a THEN or ELSE clause with a data type that the compiler can find to determine the highest data type for the expression.
A trick in the WHERE clause is use it for a complex predicate with material implications.
WHERE CASE
WHEN <search condition #1>
THEN 1
WHEN <search condition #2>
THEN 1
ELSE 0 END = 1
Gert-Jan Strik posted some exampels of how ISNULL() and COALESCE() on 2004 Aug 19
CREATE TABLE #t(a CHAR(1));
INSERT INTO #t VALUES (NULL);
SELECT ISNULL(a,'abc') FROM #t;
SELECT COALESCE(a, 'abc') FROM #t;
DROP TABLE #t;
He always use COALESCE, with the exception of the following type of
situation, because of its performance consequences:
SELECT ...,
ISNULL((SELECT COUNT(*) -- or other aggregate
FROM B
WHERE B.key = A.key), 0)
FROM A;
Likewise, Alejandro Mesa came up with this example:
SELECT 13 / COALESCE(CAST(NULL AS INTEGER), 2.00); -- promote to highest type (decimal)
SELECT 13 / ISNULL(CAST(NULL AS INTEGER), 2.00); -- promote to first type (integer)
>> if (I miss 2012 with the simple iif) the core is null write the same value that there is in technology otherwise write 'Import'... what's wrong with that? <<
Why do you want to write non_ANSI/ISO dialect? Do you like your spreadsheets that much? :(
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL -
Doubt about Select statement.
Hi folks!!
I have a few doubts about the select statements, it may be a silly things but its useful for me.
what is difference between below statment.
1)SELECT * FROM TABLE.
2)SELECT SINGLE * FROM TABLE
3)SELECT SINGLE FROM TABLE.
Hope i will get answer,thanks in advance.
Regards
Richie..Hi,
try this and if possible use sap help.i mean place the cursor on select and press F1.
Types of select statements:
1. select * from ztxlfa1 into table it.
This is simple select statement to fetch all the data of db table into internal table it.
2. select * from ztxlfa1 into table it where lifnr between 'V2' and 'V5'.
Thisis using where condition between v2 and v5.
4. select * from ztxlfa1 where land1 = 'DE'. "row goes into default table work Area
5. select lifnr land1 from ztxlfa1
into corresponding fields of it "notice 'table' is omitted
where land1 = 'DE'.
append it.
endselect.
Now data will go into work area. and then u will add it to internal table by
append statement.
6. Table 13.2 contains a list of the various forms of select as it is used with internal tables and their relative efficiency. They are in descending order of most-to-least efficient.
Table 13.2 Various Forms of SELECT when Filling an Internal Table
Statement(s) Writes To
select into table it Body
select into corresponding fields of table it Body
select into it Header line
select into corresponding fields of it Header line
7. SELECT VBRK~VBELN
VBRK~VKORG
VBRK~FKDAT
VBRK~NETWR
VBRK~WAERK
TVKOT~VTEXT
T001~BUKRS
T001~BUTXT
INTO CORRESPONDING FIELDS OF TABLE IT_FINAL
FROM VBRK
INNER JOIN TVKOT ON VBRKVKORG = TVKOTVKORG
INNER JOIN T001 ON VBRKBUKRS = T001BUKRS
WHERE VBELN IN DOCNUM AND VBRK~FKSTO = ''
AND VBRK~FKDAT in date.
Select statement using inner joins for vbrk and t001 and tvkot table for this case based on the conditions
8. SELECT T001W~NAME1 INTO TABLE IT1_T001W
FROM T001W INNER JOIN EKPO ON T001WWERKS = EKPOWERKS
WHERE EKPO~EBELN = PURORD.
here selecting a single field into table it1_t001winner join on ekpo.
9. SELECT BUKRS LIFNR EBELN FROM EKKO INTO CORRESPONDING FIELDS OF IT_EKKO WHERE EBELN IN P_O_NO.
ENDSELECT.
SELECT BUTXT FROM T001 INTO IT_T001 FOR ALL ENTRIES IN IT_EKKO WHERE BUKRS = IT_EKKO-BUKRS.
ENDSELECT.
APPEND IT_T001.
here I am using for all entries statement with select statement. Both joins and for all entries used to fetch the data on condition but for all entries is the best one.
10. SELECT AVBELN BVTEXT AFKDAT CBUTXT ANETWR AWAERK INTO TABLE ITAB
FROM VBRK AS A
INNER JOIN TVKOT AS B ON
AVKORG EQ BVKORG
INNER JOIN T001 AS C ON
ABUKRS EQ CBUKRS
WHERE AVBELN IN BDOCU AND AFKSTO EQ ' ' AND B~SPRAS EQ
SY-LANGU
AND AFKDAT IN BDATE AND AVBELN EQ ANY ( SELECT VBELN FROM
VBRP WHERE VBRP~MATNR EQ ITEMS ).
Here we are using sub query in inner join specified in brackets.
Thanks,
chandu. -
Hi all!
I have to show the inspection lot details (QA32) as per the requirements given in the selection screen.
In my selection screen , I should have select option for Inspection lot created date(QALS-ENSTEHDAT) and lot created time (QALS-ENTSTEZEIT). I would like to know the lots created from yesterday evening till today morning.
When I give the values 09.02.2008 to 10.02.2008 for date and 17:30:00 to 10:00:00 for time , it'll obviously intimate that 'From- time is greater than To- time'.Is there any way to relate the From-date to From-time and To-date to To-time in the selection screen , so that my problem will be solved.Please help with possible code.
Edited by: Jayasri P. on Feb 9, 2008 5:55 AMHi,
try this.........
TABLES qals.
DATA it_qals TYPE TABLE OF qals WITH HEADER LINE.
SELECT-OPTIONS s_date FOR qals-enstehdat NO-EXTENSION.
SELECTION-SCREEN BEGIN OF LINE.
SELECTION-SCREEN comment (10) for field p_timel.
SELECTION-SCREEN POSITION 35.
PARAMETERS p_timel LIKE qals-entstezeit.
SELECTION-SCREEN comment 54(2) for field p_timeh.
SELECTION-SCREEN POSITION 60.
PARAMETERS p_timeh LIKE qals-entstezeit.
SELECTION-SCREEN END OF LINE.
SELECT *
FROM qals
INTO TABLE it_qals
WHERE enstehdat IN s_date.
IF sy-subrc IS INITIAL.
SORT it_qals BY enstehdat entstezeit.
LOOP AT it_qals WHERE enstehdat EQ s_date-low
OR enstehdat EQ s_date-high.
CASE it_qals-enstehdat.
WHEN s_date-low.
IF it_qals-entstezeit LT p_timel.
DELETE it_qals.
ENDIF.
WHEN s_date-high.
IF it_qals-entstezeit GT p_timeh.
DELETE it_qals.
ENDIF.
ENDCASE.
ENDLOOP.
ENDIF.
LOOP AT it_qals.
WRITE : / it_qals-enstehdat ,it_qals-entstezeit.
ENDLOOP.
also goto selection text and give descriptionas below..
P_TIMEH to
P_TIMEL Time
S_DATE Date
Cheers,
jose. -
Doubt in SELECT query (11.2.0.2.0)
I have 3 tables
1. ADBO.SECMASTER_DTL_EXT_HST_TBL
2. BDBO.SECMASTER_DETAIL_EXT_HIST
3. ADBO.SPOKE_TO_HUB_SEC_MTCH_TBL
ADBO.SECMASTER_DTL_EXT_HST_TBL and BDO.SECMASTER_DETAIL_EXT_HIST have exactly the same table structure.
Now, I need to find out the records from table BDO.SECMASTER_DETAIL_EXT_HIST with the max effective_date
which do not match to the effective_date in ADBO.SECMASTER_DTL_EXT_HST_TBL. In the results table I need to report the diff effective dates from the 2 tables if they do not match.
Also, SRC_INTFC_INST has to be 140 in both 1 and 2 tables. Further security_alias of table 1 has to match with spoke_sec of table 3
and security_alias of table 2 has to match with hub_sec of table 3.
For the data I have , I am getting 2 rows whereas I am expecting only 1 row. Can anyone suggest why this is so??
SELECT
B.SECURITY_ALIAS,
TO_CHAR (C.SPOKE_PAID),
A.SECURITY_ALIAS,
TO_CHAR (C.HUB_PAID),
'SECMASTER_DETAIL_EXT_HIST',
'EFFECTIVE_DATE',
NVL ( (CAST (B.EFFECTIVE_DATE AS VARCHAR2 (100))),
'No Records Found'),
NVL ( (CAST (A.EFFECTIVE_DATE AS VARCHAR2 (100))),
'No Records Found')
FROM ADBO.SECMASTER_DTL_EXT_HST_TBL A,
(SELECT SECURITY_ALIAS, EFFECTIVE_DATE, SRC_INTFC_INST
FROM [email protected]) B,
ADBO.SPOKE_TO_HUB_SEC_MTCH_TBL C
WHERE A.SRC_INTFC_INST = 140
AND B.SRC_INTFC_INST = 140
AND A.SECURITY_ALIAS = C.spoke_sec
AND b.security_alias = C.HUB_SEC
AND TO_CHAR (a.effective_date,'DD-MON-YYYY')
<> TO_CHAR((SELECT MAX (h.effective_date)
FROM [email protected] H
where h.security_alias = b.security_alias
AND h.src_intfc_inst = b.src_intfc_inst), 'DD-MON-YYYY')
and a.security_alias='6313';
Insert into ADBO.SECMASTER_DTL_EXT_HST_TBL
(SECURITY_ALIAS, SRC_INTFC_INST, EFFECTIVE_DATE)
Values
(6313, 140, TO_DATE('05/15/2013 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
Insert into BDBO.SECMASTER_DETAIL_EXT_HIST
(SECURITY_ALIAS, SRC_INTFC_INST, EFFECTIVE_DATE)
Values
(327667, 140, TO_DATE('05/20/2013 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
Insert into BDBO.SECMASTER_DETAIL_EXT_HIST
(SECURITY_ALIAS, SRC_INTFC_INST, EFFECTIVE_DATE)
Values
(327667, 140, TO_DATE('05/15/2013 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
Insert into ADBO.SPOKE_TO_HUB_SEC_MTCH_TBL
(SPOKE_PAID, SPOKE_SEC, LAST_HELD_DATE, PREV_HELD_DATE, HUB_PAID, HUB_SEC)
Values
('L3083 ', 6313, TO_DATE('07/18/2013 22:15:46', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('07/15/2013 22:15:30', 'MM/DD/YYYY HH24:MI:SS'), 'L3083 ',
327667);
CREATE TABLE ADBO.SECMASTER_DTL_EXT_HST_TBL
SECURITY_ALIAS NUMBER NOT NULL,
SRC_INTFC_INST NUMBER NOT NULL,
EFFECTIVE_DATE DATE NOT NULL
CREATE TABLE BDBO.SECMASTER_DETAIL_EXT_HIST
SECURITY_ALIAS NUMBER,
SRC_INTFC_INST NUMBER,
EFFECTIVE_DATE DATE
CREATE TABLE ADBO.SPOKE_TO_HUB_SEC_MTCH_TBL
SPOKE_PAID VARCHAR2(100 BYTE),
SPOKE_SEC NUMBER,
LAST_HELD_DATE DATE,
PREV_HELD_DATE DATE,
HUB_PAID VARCHAR2(100 BYTE),
HUB_SEC NUMBERHi,
one suggestion. Don't include schema in the table.
I have created your tables in my db with the following names:
a_secmaster_dtl_ext_hst_tbl
b_secmaster_detail_ext_hist
spoke_to_hub_sec_mtch_tbl
You query may be solved in this way maybe, according to what I have understood in the previous post.
with table_a as
select a.security_alias
, c.spoke_paid
, c.hub_paid
, a.effective_date
from a_secmaster_dtl_ext_hst_tbl a
join spoke_to_hub_sec_mtch_tbl c
on (a.security_alias=c.spoke_sec)
where a.src_intfc_inst = 140
and a.effective_date = (select max(a2.effective_date)
from a_secmaster_dtl_ext_hst_tbl a2
where a.security_alias=a2.security_alias
and a.src_intfc_inst=a2.src_intfc_inst)
, table_b as
select b.security_alias
, c.spoke_paid
, c.hub_paid
, b.effective_date
from b_secmaster_detail_ext_hist b
join spoke_to_hub_sec_mtch_tbl c
on (b.security_alias=c.hub_sec)
where b.src_intfc_inst = 140
and b.effective_date = (select max(b2.effective_date)
from b_secmaster_detail_ext_hist b2
where b.security_alias=b2.security_alias
and b.src_intfc_inst=b2.src_intfc_inst)
select b.security_alias
, a.spoke_paid
, a.security_alias
, b.hub_paid
, 'SECMASTER_DETAIL_EXT_HIST' txt1
, 'EFFECTIVE_DATE' txt2
, nvl(to_char(b.effective_date,'dd-mon-yyyy'), 'No Records Found') b_eff_date
, nvl(to_char(a.effective_date,'dd-mon-yyyy'), 'No Records Found') a_eff_date
from table_a a full outer join table_b b on(a.spoke_paid=b.hub_paid)
where a.effective_date!=b.effective_date;
I have used full outer join to join the table to cover the case where records are present in table a and not in table b and the opposite.
Regards.
Alberto -
Hi frnds,
Normally select option allowing only 8 charactor in declaration part, but i want to display with morethan 8 charator. i think some text id formet is there, how to do that.
for ex,
s_org for vbak-vkorg .
for this i want to give sales organisation.
how to do this.
plz its urgent.
GowriSELECTION-SCREEN BEGIN OF LINE.
[SELECTION-SCREEN POSITION pos [ldb_additions]].
SELECTION-SCREEN END OF LINE.
Effect
The first and last statements define a new line below the existing elements on the selection screen.
All the screen elements within these statements that are defined with PARAMETERS SELECT-OPTIONS and SELECTION-SCREEN statements are placed in this line one after the other without spaces.
Several SELECTION-SCREEN POSITION statements can be listed within the definition of a line. The SELECTION-SCREEN POSITION statement can be used to define the output position for the following screen element. The position pos can either be specified directly as a number between 1 and 83 or using pos_low or pos_high expressions. The expression pos_low specifies the position in which the input field for a parameter or the first input field for a selection criterion is displayed as standard. The expression pos_high specifies the position in which the second input field for a selection criterion is to be displayed as standard. If you make a different specification of the position in the statement defining the following element, this is taken into account. The statement SELECTION-SCREEN POSITION is only possible within the definition of a line. If there are conflicts with existing screen elements, the selection screen cannot be generated.
The additions ldb_additions can only be used in a selection include for a logical database.
The following applies in the definition of a line:
Output fields are not created for selection texts for the parameters displayed in these kinds of lines. Instead, these can be created by specifying a SELECTION-SCREEN COMMENT.
You cannot define other lines with SELECTION-SCREEN BEGIN OF LINE.
You cannot define blocks or tabstrip controls with SELECTION-SCREEN BEGIN OF [TABBED] BLOCK.
Within a line, only one selection criteria should be defined with SELECT-OPTIONS whose description can be specified in advance using SELECTION-SCREEN COMMENT. Other combinations, especially definitions of elements according to the selection criteria, can lead to an undefined behaviour.,
The backslash (/) is not allowed when giving format specifications.
You can omit the position specification pos in formatting specifications.
Note
If a screen element is assigned a position greater than 83 or is positioned outside a block with a frame, the selection screen is not generated. In the case of input and output fields that were positioned beforehand but have a length that extends beyond the end of the line, the visible length is shortened accordingly and the content is displayed in the visible length and can be scrolled. In this case, pushbuttons and horizontal lines are cut off at position 83 or where the frame of the block ends.
Example
A pushbutton, an input field, and an output field in a line in the standard selection screen for an executable program.
SELECTION-SCREEN: BEGIN OF LINE,
PUSHBUTTON 2(10) push USER-COMMAND fcode,
POSITION 16.
PARAMETERS para TYPE c LENGTH 20.
SELECTION-SCREEN: COMMENT 40(40) text,
END OF LINE.
INITIALIZATION.
push = 'Push'.
text = '<--- Fill field, then push button!'.
Maybe you are looking for
-
MSS IAC reporting error?
Hi, We created custom MSS role which has limited services from standard MSS role. So we didn't want to make any change to the standard MSS role. One of the service under custom MSS role is reporting we made it to point to reporting page(PCD as belo
-
How to define the number of tab displayed in Tab page group
Hello, I have an application with Tab Page group with 8 tabs and the browser is displaying only 5 of thems. I have to scroll to display the remaining 3 although I have enough spaces on the screen to displayed all of them. Do you know what parameter/
-
how deal with when u are trading with different branch offices of company.
-
URGENT: iframe in a dynamic page. Strange Problem.
Hi all, I have a typical problem. I created a Dynamic Page which brings out the information of a Purchase Order (PO). (PO_REPORT) Now the numer of items in a PO can vary from 1 to anything.... so I made a seperated report based on sql query (ITEM_DET
-
Hi there, Just got my Apple TV and hooked it up to a Sony widescreen TV (8 yrs old) through component video (to scart). Video modus 576i works... but only in black and white. Tried it on another Sony TV, but exact the same result. What am I doing wro