Use CASE in HAVING clause
I feel like this should be simple but it I'm just not grasping it.
Say I have this query:
SELECT order_number, order_date FROM orders
I basically want to pull any order from the last 24 hours. Well this is fairly easy for Tue-Fri but when I run the query on Mon, it will have zero results since there are no orders from the weekend. If the query is ran on Mon it should query
Fri instead.
I'm attempting to use case in my having clause but no luck.
HAVING (DATEDIFF(dd, GETDATE(), order_date = (CASE order_date WHEN DATENAME(weekday,getdate()) = 'Friday' THEN '3' ELSE '0' END)
Sure my syntax or parentheses is way off, any help is appreciated. Thanks.
Check out the following CASE expression:
SELECT CASE WHEN datename(dw,getdate()) = 'Monday' THEN
CONVERT(DATE,(SELECT dateadd(d, -((datepart(weekday, getdate()) + 1 + @@DATEFIRST) % 7), getdate())))
ELSE CONVERT(DATE, DATEADD(dd, -1, getdate())) END;
/********* TEST ****************/
DECLARE @Dt datetime;
DECLARE @i int = 0; WHILE (@i < 10) BEGIN
SET @Dt = dateadd(dd, @i, getdate());
SELECT Today = @Dt, WeekDay=DATENAME(dw,@Dt), PrevBusinessDay= CASE WHEN datename(dw,@Dt) = 'Monday' THEN
CONVERT(DATE, (SELECT dateadd(d, -((datepart(weekday, @Dt) + 1 + @@DATEFIRST) % 7), @Dt)))
ELSE CONVERT(DATE, DATEADD(dd, -1, @Dt)) END;
SET @i += 1; END -- WHILE
Today WeekDay PrevBusinessDay
2014-06-20 19:46:45.130 Friday 2014-06-19
Today WeekDay PrevBusinessDay
2014-06-23 19:49:04.817 Monday 2014-06-20
Today WeekDay PrevBusinessDay
2014-06-24 19:46:45.130 Tuesday 2014-06-23
Today WeekDay PrevBusinessDay
2014-06-25 19:46:45.130 Wednesday 2014-06-24
Today WeekDay PrevBusinessDay
2014-06-26 19:46:45.130 Thursday 2014-06-25
Today WeekDay PrevBusinessDay
2014-06-27 19:46:45.130 Friday 2014-06-26
Datetime functions:
http://www.sqlusa.com/bestpractices/datetimeconversion/
Consider also implementation with a calendar table.
Kalman Toth Database & OLAP Architect
SQL Server 2014 Design & Programming
New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012
Similar Messages
-
Can we use Case in Where Clause along with Exists
Hi Everybody,
Can we use Case in the where clause with exists? As i have a requirement in which i have to check whether value exists in 6 views, now depending on some value(gns_type )of select clause i have to attach a paticular exists else the performance dies.
Please go through the query any suggestion appreciated.
Thanks
SELECT count(*)
FROM
(SELECT eah.changed_date,
decode(eua.is_deleted, 'N', decode(eah.alert_type, NULL, 'GN', 'R', 'GAR', 'G', 'GAG', 'Y', 'GAY'), 'Y', decode(eah.alert_type, 'R', 'GDR', 'G', 'GDG', 'Y', 'GDY', NULL, 'GN'), NULL, 'GN') AS
alert_type,
decode(eac.pta_line, 'N', '') ptaline,
eac.exp_type_desc,
eac.supplier_name,
eac.transaction_id,
eah.gns_type,
eac.po_amount,
eac.po_end_date,
eah.notes,
eua.is_deleted,
eac.expenditure_type,
eua.gns_alert_summary_id,
eah.changed_date alert_date,
eua.user_alert_id,
eah.reference_number,
decode(eac.cms_pta_line,'N','',eac.cms_pta_line) cms_pta_line,
cms_po_amount,
cms_po_end_date,
mgns.is_decommitted,
eac.gns_alert_id,
eah.gns_type source_name
FROM xxdl.xxdl_sc_gns_alerts_summary eah,
xxdl.xxdl_sc_gns_detail_alerts eac,
xxdl.xxdl_sc_gns_user_alerts eua,
xxdl.xxdl_sc_manage_gns_master mgns
WHERE eah.gns_alert_summary_id = eac.gns_alert_summary_id
AND eah.gns_alert_summary_id = eua.gns_alert_summary_id
AND eah.transaction_id = eac.transaction_id
AND eah.transaction_id = mgns.transaction_id)
a
WHERE(EXISTS
(SELECT 1
FROM xxdl_sc_mng_gns_pta_req_hc_v x
WHERE x.transaction_id = a.transaction_id
AND x.source_name = a.source_name
AND x.project_id = 69309
AND x.task_id = 242528
AND x.award_id = 34694)
OR
EXISTS( SELECT 1
FROM xxdl_sc_mng_gns_pta_inv_hc_v x
WHERE x.transaction_id = a.transaction_id
AND x.source_name = a.source_name
AND x.project_id = 69309
AND x.task_id = 242528
AND x.award_id = 34694)
OR
EXISTS(SELECT 1
FROM xxdl_sc_mng_gns_pta_req_sc_v x
WHERE x.transaction_id = a.transaction_id
AND x.source_name = a.source_name
AND x.project_id = 69309
AND x.task_id = 242528
AND x.award_id = 34694)
OR
EXISTS(SELECT 1
FROM xxdl_sc_mng_gns_pta_inv_sc_v x
WHERE x.transaction_id = a.transaction_id
AND x.source_name = a.source_name
AND x.project_id = 69309
AND x.task_id = 242528
AND x.award_id = 34694)
OR
EXISTS( SELECT 1
FROM xxdl_sc_mng_gns_pta_po_sc_v x
WHERE x.transaction_id = a.transaction_id
AND x.source_name = a.source_name
AND x.project_id = 69309
AND x.task_id = 242528
AND x.award_id = 34694)
OR
EXISTS (SELECT 1
FROM xxdl_sc_mng_gns_pta_po_hc_v x
WHERE x.transaction_id = a.transaction_id
AND x.source_name = a.source_name
AND x.project_id = 69309
AND x.task_id = 242528
AND x.award_id = 34694)
AND TRUNC(alert_date) >= TRUNC(add_months(sysdate, -1))
AND TRUNC(alert_date) <= TRUNC(sysdate)
AND is_deleted = 'N'
ORDER BY changed_date DESCyou can do
WHERE
CASE WHEN (something) THEN
CASE WHEN EXISTS (SELECT * from ...) THEN 1 ELSE 0 END
WHEN (something else) THEN
CASE WHEN EXISTS (SELECT * from ...) THEN 1 ELSE 0 END
END = 1Looking at your current query, it looks like all those exist statements could be a lot neater, maybe like:
WHERE (69309,242528,34694) IN
(SELECT project_id,task_id,award_id FROM
(Select project_id,task_id,award_id,transaction_id,source_name
FROM
xxdl_sc_mng_gns_pta_req_hc_v
UNION ALL
Select project_id,task_id,award_id
xxdl_sc_mng_gns_pta_inv_hc_v
...) x
where a.transaction_id = x.transaction_id
and a.source_name = x.source_name
)or put the tuple in the where clause at the bottom -
Using CASE on WHERE clause?
Is it posible to use a CASE on the WHERE clause?
I always used the following syntax on MSSQL
but Oracle aparently doesn't accept it:
SELECT...
WHERE
CASE WHEN keyword IS NOT NULL THEN
CONTAINS(field, keyword) > 0
END AND
CASE WHEN varcode IS NOT NULL THEN
code = varcode
END AND
OTHER STATEMENTSSQL> SELECT
2 COUNT(*) OVER() total,
3 ed_fotos.id AS COD_FOTO,
4 ed_fotos.foto.getwidth()/100 AS VLR_LARGURA,
5 ed_fotos.foto.getheight()/100 AS VLR_ALTURA,
6 ed_fotos.arquivo AS NOM_ARQUIVO,
7 ed_areas.nome AS NOM_REDACAO
8 FROM edt.ed_fotos ed_fotos
9 INNER JOIN edt.ed_areas ed_areas ON
10 ed_areas.id = ed_fotos.redacao_id AND
11 (ed_areas.ind_licenciada <> 'S' OR
12 ed_areas.ind_licenciada IS NULL
13 OR (ed_areas.id IN (SELECT * FROM THE (SELECT CAST(fda_
adm.in_list('') AS fda_adm.mytableType) FROM dual)))
14 )
15 LEFT JOIN edt.ed_creditos_fotos ed_creditos_fotos ON
16 ed_creditos_fotos.foto_id = ed_fotos.id
17 LEFT JOIN edt.ed_itens ed_itens ON
18 ed_itens.foto_id = ed_fotos.id
19 LEFT JOIN edt.ed_edicoes ed_edicoes ON
20 ed_edicoes.id = ed_itens.edicao_id
21 LEFT JOIN edt.vw_dedoc_ccda vw_dedoc_ccda ON
22 vw_dedoc_ccda.num_ccda = ed_fotos.num_ccda_sct AND
23 vw_dedoc_ccda.cod_tipo_documento IN ('B','C','C1','C2')
24 LEFT JOIN fda_adm.vw_lui vw_lui ON
25 vw_lui.foto_id = ed_fotos.id AND
26 vw_lui.cod_tipo_documento IN ('B','C')
27 WHERE
28 CASE WHEN 'BUSH' IS NOT NULL THEN
29 CONTAINS(ed_fotos.detalhe, '{BUSH} within termo
OR {BUSH} within headline OR {BUSH} within desc') > 0
30 END) AND
31 1 = 1
32 GROUP BY
33 ed_fotos.id,
34 ed_fotos.foto.getwidth(),
35 ed_fotos.foto.getheight(),
36 ed_fotos.registro,
37 ed_fotos.arquivo,
38 ed_areas.nome,
39 ed_areas.id
40 ORDER BY
41 ed_fotos.id DESC
42 /
CONTAINS(ed_fotos.detalhe, '{BUSH} within termo
OR {BUSH} within headline OR {BUSH} within desc') > 0
ERRO on line 29:
ORA-00905: missing keyword -
Group by clause and having clause in select
hi frnds
plz give me some information of group by and having clause used in select statement with example
thanksThe Open SQL statement for reading data from database tables is:
SELECT <result>
INTO <target>
FROM <source>
[WHERE <condition>]
[GROUP BY <fields>]
[HAVING <cond>]
[ORDER BY <fields>].
The SELECT statement is divided into a series of simple clauses, each of which has a different part to play in selecting, placing, and arranging the data from the database.
You can only use the HAVING clause in conjunction with the GROUP BY clause.
To select line groups, use:
SELECT <lines> <s1> [AS <a1>] <s2> [AS <a2>] ...
<agg> <sm> [AS <am>] <agg> <sn> [AS <an>] ...
GROUP BY <s1> <s2> ....
HAVING <cond>.
The conditions <cond> that you can use in the HAVING clause are the same as those in the SELECT clause, with the restrictions that you can only use columns from the SELECT clause, and not all of the columns from the database tables in the FROM clause. If you use an invalid column, a runtime error results.
On the other hand, you can enter aggregate expressions for all columns read from the database table that do not appear in the GROUP BY clause. This means that you can use aggregate expressions, even if they do not appear in the SELECT clause. You cannot use aggregate expressions in the conditions in the WHERE clause.
As in the WHERE clause, you can specify the conditions in the HAVING clause as the contents of an internal table with line type C and length 72.
Example
DATA WA TYPE SFLIGHT.
SELECT CONNID
INTO WA-CONNID
FROM SFLIGHT
WHERE CARRID = 'LH'
GROUP BY CONNID
HAVING SUM( SEATSOCC ) > 300.
WRITE: / WA-CARRID, WA-CONNID.
ENDSELECT.
This example selects groups of lines from database table SFLIGHT with the value LH for CARRID and identical values of CONNID. The groups are then restricted further by the condition that the sum of the contents of the column SEATSOCC for a group must be greater than 300.
The <b>GROUP BY</b> clause summarizes several lines from the database table into a single line of the selection.
The GROUP BY clause allows you to summarize lines that have the same content in particular columns. Aggregate functions are applied to the other columns. You can specify the columns in the GROUP BY clause either statically or dynamically.
Specifying Columns Statically
To specify the columns in the GROUP BY clause statically, use:
SELECT <lines> <s1> [AS <a 1>] <s 2> [AS <a 2>] ...
<agg> <sm> [AS <a m>] <agg> <s n> [AS <a n>] ...
GROUP BY <s1> <s 2> ....
To use the GROUP BY clause, you must specify all of the relevant columns in the SELECT clause. In the GROUP BY clause, you list the field names of the columns whose contents must be the same. You can only use the field names as they appear in the database table. Alias names from the SELECT clause are not allowed.
All columns of the SELECT clause that are not listed in the GROUP BY clause must be included in aggregate functions. This defines how the contents of these columns is calculated when the lines are summarized.
Specifying Columns Dynamically
To specify the columns in the GROUP BY clause dynamically, use:
... GROUP BY (<itab>) ...
where <itab> is an internal table with line type C and maximum length 72 characters containing the column names <s 1 > <s 2 > .....
Example
DATA: CARRID TYPE SFLIGHT-CARRID,
MINIMUM TYPE P DECIMALS 2,
MAXIMUM TYPE P DECIMALS 2.
SELECT CARRID MIN( PRICE ) MAX( PRICE )
INTO (CARRID, MINIMUM, MAXIMUM)
FROM SFLIGHT
GROUP BY CARRID.
WRITE: / CARRID, MINIMUM, MAXIMUM.
ENDSELECT.
regards
vinod -
Why Scalar Subquery expression cannot be used in HAVING clauses?
Hi All,
I'm new to SQL. I'm confused with Scalar Subquery.
Is there anyone who can answer me why Scalar Subquery expression cannot be used in HAVING clauses.
Can you show me a example?
Thanks very much,
Xianyi.Ye
Edited by: 908428 on 2012-1-16 下午7:24Hi,
908428 wrote:
Hi Frank,
Thank you for your quick reply. I also agree with your point.
But when I read the book, "OCA Oracle Database SQL Certified Expert Exam Guide",( link to illegal copies of book removed by moderator )
on Page 359, it said that
Scalar subquery expressions cannot be used in the following locations:
1. In CHECK constraints
2. In GROUP BY clauses
3. In HAVING clauses
4. In a function-based index (which is coming up in Chapter 11)
5. As a DEFAULT value for a column
6. In the RETURNING clause of any DML statement
7. In the WHEN conditions of CASE
8. In the START WITH and CONNECT BY clauses, which we discuss in
Chapter 16.7 and 8 are wrong. Scalar sub-queries can be used in WHEN conditions and START WITH and CONNECT BY clauses. (At least in Oracle 10.2. Is the book based on some earlier version?)
Edited by: BluShadow on 17-Jan-2012 09:08 -
Use of Where and having clause
Hi all,
I always have a doubt about use of HAVING and WHERE clause,
suppose I have table T1 with only one column C1
CREATE TABLE T1
(C1 VARCHAR2(1) );
which having data by following INSERT scripts
INSERT INTO T1 VALUES('A');
INSERT INTO T1 VALUES('B');
INSERT INTO T1 VALUES('C');
INSERT INTO T1 VALUES('A');
INSERT INTO T1 VALUES('B');
INSERT INTO T1 VALUES('A');
Now I want result as follows
C1 ==== COUNT(C1)
==============
B ===== 2
A ===== 3
So out of query 1 and 2 which approach is right ?
1) SELECT C1,COUNT(C1) FROM T1
WHERE C1<>'C'
GROUP BY C1
ORDER BY C1 DESC;
2) SELECT C1,COUNT(C1) FROM T1
GROUP BY C1
HAVING C1<>'C'
ORDER BY C1 DESC;
Edited by: user13306874 on Jun 21, 2010 2:36 AMIn SQL, it's always best to filter data at the earliest moment possible.
In your example the WHERE clause would be that moment:
SQL> explain plan for
2 select c1,count(c1)
3 from t1
4 where c1 != 'C'
5 group by c1
6* order by c1 desc;
Explained.
SQL> select * from table(dbms_xplan.display);
PLAN_TABLE_OUTPUT
Plan hash value: 3946799371
| Id | Operation | Name | Rows | Bytes |
| 0 | SELECT STATEMENT | | 5 | 10 |
| 1 | SORT GROUP BY | | 5 | 10 |
|* 2 | TABLE ACCESS FULL| T1 | 5 | 10 |
Predicate Information (identified by operation id):
2 - filter("C1"!='C')
18 rows selected.
SQL>As you can see the filter is applied during the scan of T1.
Whereas in the HAVING case:
SQL> explain plan for
2 select c1,count(c1)
3 from t1
4 group by c1
5 having c1 != 'C'
6* order by c1 desc;
Explained.
SQL> select * from table(dbms_xplan.display);
PLAN_TABLE_OUTPUT
Plan hash value: 3146800528
| Id | Operation | Name | Rows | Bytes |
| 0 | SELECT STATEMENT | | 6 | 12 |
|* 1 | FILTER | | | |
| 2 | SORT GROUP BY | | 6 | 12 |
| 3 | TABLE ACCESS FULL| T1 | 6 | 12 |
Predicate Information (identified by operation id):
1 - filter("C1"!='C')
18 rows selected.
SQL>The scan is done after all groups have been computed: one of which was computed in vain, since it will be filtered away due to the HAVING clause.
In general I would use as a guideline: if you are not using aggregate functions in your HAVING clause predicate, then move that predicate to the WHERE portion of your query.
Edited by: Toon Koppelaars on Jun 21, 2010 11:54 AM -
Using case when statement or decode stament in where clause
hi gems..
i have a problem in the following query..
i am trying to use case when statement in the where clause of a select query.
select cr.customer_name || ' - ' ||cr.customer_number as cust_name,
cr.salary as salary
from customer_details cr
where (case when '>' = '>' then 'cr.salary > 5000'
when '>' = '<' then 'cr.salary < 5000'
when '>' = '=' then 'cr.salary = 5000'
else null
end);
the expression in the when clause of the case-when statement will come from UI and depending on the choice i need to make the where clause.
thats why for running the query, i have put '>' in that place.
so the original query will look like this(for your reference):
select cr.customer_name || ' - ' ||cr.customer_number as cust_name,
cr.salary as salary
from customer_details cr
where (case when variable = '>' then 'cr.salary > 5000'
when variable = '<' then 'cr.salary < 5000'
when variable = '=' then 'cr.salary = 5000'
else null
end);
so, in actual case,if the user selects '>' then the filter will be "where cr.salary > 5000"
if the user selects '<' then the filter will be "where cr.salary < 5000"
if the user selects '=' then the filter will be "where cr.salary = 5000"
but i am getting the error "ORA 00920:invalid relational operator"
please help..thanks in advance..Hi,
select cr.customer_name || ' - ' ||cr.customer_number as cust_name,
cr.salary as salary
from customer_details cr
where ( v_variable = 'bigger'
and cr.salary > 5000
or ( v_variable = 'less'
and cr.salary < 5000
or ( v_variable = 'eq'
and cr.salary = 5000
)Edited by: user6806750 on 22.12.2011 14:56
For some reason I can't write in sql '<', '>', '=' -
How to use case function in where clause
Hi,
Suppose a table DEMO has columns
DEMO TABLE
user_id
user_name
location
In this table i have 15 users. but out of 15 users i want to use only 5 users for passing as user_name.
then how to achieve the result
1. when i pass the particular 5 user_name in where clause then i should get all the user_name and for other 10 users it will show only the passing user_name.
how to use case functionDo you mean this ?
SQL> var name varchar2(10)
SQL> exec :name := 'ALLEN'
PL/SQL procedure successfully completed.
SQL> select ename from emp where case when :name in ('SMITH','ALLEN') then ename
2 else :name end = ename;
ENAME
SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
JAMES
FORD
MILLER
14 rows selected.
SQL> exec :name := 'SMITH'
PL/SQL procedure successfully completed.
SQL> select ename from emp where case when :name in ('SMITH','ALLEN') then ename
2 else :name end = ename;
ENAME
SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
JAMES
FORD
MILLER
14 rows selected.
SQL> exec :name := 'BLAKE'
PL/SQL procedure successfully completed.
SQL> select ename from emp where case when :name in ('SMITH','ALLEN') then ename
2 else :name end = ename;
ENAME
BLAKERgds. -
How to Use SQL Query having IN Clause With DB Adapter
Hi,
I am using 11.1.1.5 want to find out how to Use SQL Query having IN Clause With DB Adapter. I want to pass the IN values dynamically. Any ideas.
Thanksinvoke a stored procedure, it's safer than trying to put together an arbitrary SQL statement in the JCA adapter
-
How to use CASE stmt in Where clause
Hi,
How to use CASE stmt in WHERE clause?. I need the code. Please send me as early as possible..........Hi,
1004977 wrote:
Hi,
How to use CASE stmt in WHERE clause?. There's no difference between how a CASE expression is used in a WHERE clause, and how it is used in any other clause. CASE ... END always returns a single scalar value, and it can be used almost anywere a single scalar expression (such as a column, a literal, a single-row function, a + operation, ...) can be used.
CASE expressions aren't needed in WHERE clauses very much. The reason CASE expressions are so useful is that they allow you to do IF-THEN-ELSE logic anywhere in SQL. The WHERE clause already allows you to do IF-THEN-ELSE logic, usually in a more convenient way.
I need the code.So do the peple who want t help you. Post a query where you'd like to use a CASE expression in the WHERE clause. Post CREATE TABLE and INSERT statements for any tables used unless they are commonly available, such as scott.emp). Also, post the results you want from that sample data, and explain how you get those resuts from that data.
See the forum FAQ {message:id=9360002}
Please send me as early as possible..........As mentioned bfore, that's rude. It's also self-defeating. Nobody will refuse to help you because you don't appear pushy enough, but some people will refuse to help you if you appear too pushy. -
Query Tuning - using CASE statement in the WHERE clause - Duplicate Post
Duplicate Post by mistake.
Please check
Query Tuning - using CASE statement in the WHERE clause
Edited by: Chaitanya on Jun 9, 2011 2:45 AM
Edited by: Chaitanya on Jun 9, 2011 2:46 AMDuplicate Post by mistake.
Please check
Query Tuning - using CASE statement in the WHERE clause
Edited by: Chaitanya on Jun 9, 2011 2:45 AM
Edited by: Chaitanya on Jun 9, 2011 2:46 AM -
Use of group by and having clause
hi frnds
can anybody explain me the use of group by an having clause in select state mentHi Rohit,
1. GROUP BY f1 ... fn
2. GROUP BY (itab)
1. GROUP BY f1 ... fn
Effect
Groups database table data in a SELECT command on one line in the result set. A group is a set of lines which all have the same values in each column determined by the field descriptors f1 ... fn.
... GROUP BY f1 ... fn always requires a list in the SELECT clause. If you use field descriptors without an aggregate funciton in the SELECT clause, you must list them in the GROUP BY f1 ... fn clause.
Example
Output the number of passengers, the total weight and the average weight of luggage for all Lufthansa flights on 28.02.1995:
TABLES SBOOK.
DATA: COUNT TYPE I, SUM TYPE P DECIMALS 2, AVG TYPE F.
DATA: CONNID LIKE SBOOK-CONNID.
SELECT CONNID COUNT( * ) SUM( LUGGWEIGHT ) AVG( LUGGWEIGHT )
INTO (CONNID, COUNT, SUM, AVG)
FROM SBOOK
WHERE
CARRID = 'LH' AND
FLDATE = '19950228'
GROUP BY CONNID.
WRITE: / CONNID, COUNT, SUM, AVG.
ENDSELECT.
Note
... GROUP BY f1 ... fn is not supported for pooled and cluster tables.
2. GROUP BY (itab)
Effect
Works like GROUP BY f1 ... fn if the internal table itab contains the list f1 ... fn as ABAP source code. The internal table itab can only have one field. This field must be of the type C and should not be more than 72 characters long. itab must be enclosed in parentheses and there should be no blanks between the parentheses and the table name.
Note
The same restrictions apply to this variant as to GROUP BY f1 ... fn.
Example
Output all Lufthansa departure points with the number of destinations:
TABLES: SPFLI.
DATA: BEGIN OF WA.
INCLUDE STRUCTURE SPFLI.
DATA: COUNT TYPE I.
DATA: END OF WA.
DATA: WA_TAB(72) TYPE C,
GTAB LIKE TABLE OF WA_TAB,
FTAB LIKE TABLE OF WA_TAB,
COUNT TYPE I.
CLEAR: GTAB, FTAB.
WA_TAB = 'COTYFROM COUNT( * ) AS COUNT'. APPEND FTAB.
APPEND WA_TAB TO FTAB.
WA_TAB = 'CITYFROM'.
APPEND WA_TAB TO GTAB.
SELECT DISTINCT (FTAB)
INTO CORRESPONDING FIELDS OF WA
FROM SPFLI
WHERE
CARRID = 'LH'
GROUP BY (GTAB).
WRITE: / WA-CITYFROM, WA-COUNT.
ENDSELECT.
Regards,
Susmitha -
Need help in this sql query to use Case Statement
hi All,
I have the below query -
SELECT DISTINCT OFFC.PROV_ID
,OFFC.WK_DAY
,CASE
WHEN OFFC.WK_DAY ='MONDAY' THEN 1
WHEN OFFC.WK_DAY ='TUESDAY' THEN 2
WHEN OFFC.WK_DAY ='WEDNESDAY' THEN 3
WHEN OFFC.WK_DAY ='THURSDAY' THEN 4
WHEN OFFC.WK_DAY ='FRIDAY' THEN 5
WHEN OFFC.WK_DAY ='SATURDAY' THEN 6
WHEN OFFC.WK_DAY ='SUNDAY' THEN 7
END AS DOW
,OFFC.OFFC_OPENG_TIME
,OFFC.OFFC_CLSNG_TIME
FROM GGDD.PROV_OFFC_HR OFFC
WHERE OFFC.PROV_ID='0000600'
WITH UR;
this query is bringing results in 6 differnt rows with opening and closing time for each day separately. I want to generate the data in one row with each day having opening and closing time, so for 7 days, total 14 columns with opening and closing time. But i am not able to do that using case statement.
can somebody help me in achieving that.
thanks,
iamhereHi,
Welcome to the forum!
That's called a Pivot .
Instead of having 1CASE expression, have 14, one for the opening and one for the closing time each day, and do GROUP BY to combine them onto one row.
SELECT OFFC.PROV_ID
, MIN (CASE WHEN OFFC.WK_DAY ='MONDAY' THEN OFFC.OFFC_OPENG_TIME END) AS mon_opn
, MIN (CASE WHEN OFFC.WK_DAY ='MONDAY' THEN OFFC.OFFC_CLSNG_TIME END) AS mon_cls
, MIN (CASE WHEN OFFC.WK_DAY ='TUESDAY' THEN OFFC.OFFC_OPENG_TIME END) AS tue_opn
, MIN (CASE WHEN OFFC.WK_DAY ='TUESDAY' THEN OFFC.OFFC_CLSNG_TIME END) AS tue_cls
FROM GGDD.PROV_OFFC_HR OFFC
WHERE OFFC.PROV_ID = '0000600'
GROUP BY offc.prov_id
;This assumes there is (at most) only one row in the table for each distinct prov_id and weekday. If not, what do you want to do? Post a little sample data (CREATE TABLE and INSERT statements) and the results you want from that data.
The staement above works in Oracle 8.1 and up, but there's a better way (SELECT ... PIVOT) available in Oracle 11. What version are you using? (It's always a good idea to include this when you post a question.)
Edited by: Frank Kulash on Jan 6, 2011 8:22 PM -
Hi all
We can use decode function in the Select columns as well as Group by Columns as well as Having Clause
Can we use decode function in the where clause also. If yes can u give small sample
Suresh Bansal""DECODE in the WHERE clause"
http://psoug.org/reference/decode_case.html
WHERE empid = DECODE(posn,
0, st.areadir,
1, st.areamgr,
2, NVL(st.storemgr1, st.storemgr2),
3, NVL(st.asstmgr1, NVL(st.asstmgr2,
st.asstmgr3))) -
Urgent Group by Having Clause Fails in Oracle and Works in Sybase
Hello EveryBody I need to select curve data of curve whose date is maximum in that curve so say if i ahve
so if records are
curveid curvename curvedate
1001 test1 12/12/1003
1001 test1 12/13/1003
1002 test2 12/12/2002
1002 test2 12/12/2004
I have query which run well in sybase but oracle screw up...My logic say having clause is use to filter the records of group so it should have worked in oracle.....
Here is query
select curveid,curvename from curve group by curveid having curvedate =max(curve_date)
This give "not a Group by " error in oracle....It work well in sybase...
ORA-00979: not a GROUP BY expression
I have query which use subquery to select these records but i don't want that to use that query
Please helpplease understand what I need the result
for each curve i need that data of that curve who date is max in that curve group
so say for 1001 there are two date 1/1/2001 and 1/1/2002
I need the data of curve 1001 with date 1/1/2002
Oracle should have some alternative solution for this....
If i have to use subquery I do have subquery
select a.curveid, b.curvename from curve a group by curveid having curvedate = (select max(curvedate) from curve where a.curveid=b.curveid group by curveid );
I don't want to use that ,,,
I want to solve my probelm using having and group/....
Main purpose of having is to filter the records from group result so IT SHOULD DO THAT WHY ORACLE GIVE ORA ERROR FOR
group by curve_id having curve_date=max(curve_date)
Creators of oracle please reply
Maybe you are looking for
-
Problem when using a different data element in Employee Tab Contact Info
Hello, My version: Nakisa OrgChart 4.1 I created a data element whose fields I wanted to show in the Position details (in the Employee Profile panel, which use the default Static layout 'Employee Tabs'). I am trying to display some contact info, and
-
Linksys SGE2010P resets after power off
Hello, i got a linksys SGE2010P and when i configure it and save it works fine but after a power off the settings are back to default. someone an idea ? Rensk, Solved! Go to Solution.
-
Maintain back ground activity while file dialog pop is open
If i use a labview pop for example file dialog pop up and i put in an event stracture,the event case doesn't come back to the timeout case till the user closes the pop up(it could be by clicking ok or cancel)..is there a way of making it that as the
-
Video preview very slow. Is my hardware fine? (CS4)
I've searched around the internet and apparently this is a fairly common problem people have. Sadly, despite the commonality, I couldn't find any definitive fix or solution for these problems. My PC isnt the best ever, but it can handle itself. Graph
-
Hi All, Please give me an insight here, we have a lot of macintosh and windowses clients right now, can anyone please help give an insight on what am i going to setup as the authentication services whether AD or OD, i have not much knowledge in AD, m