Grouping rows from a query
Hi everyone!
I want to know if it's posible to group the rows from a query into a unique row. Example:
SELECT Field_1 FROM Table_1
Returns the following fileds:
Field_1
A
B
C
D
I would want to modify my query so that the result obtained would be a single row containing all the others. In the previous example the result would be "ABCD".
Thanks in advance. Best regards,
-- For anyone who wants to test this,
-- just copy this entire post as is,
-- save it to a .sql file, then start that file.
-- Before doing this,
-- make sure that you don't already have
-- a table named table_1 that would be dropped
-- or a .sql file named query.sql that would be overwritten.
-- If you do, then change the names below to avoid any conflicts.
-- In order to understand what the code is doing,
-- please read all of the comments included in this file,
-- as not everything is displayed when you run it.
-- I have gone into great detail with this
-- because I have posted similar things before
-- and a lot of people have total missed the fact
-- that it is not a static query,
-- that the results are dependent upon the number of rows,
-- and that it works for any number of rows,
-- even when the number of rows is unknonwn.
-- test data:
DROP TABLE table_1
CREATE TABLE table_1
(field_1 VARCHAR2 (1))
INSERT INTO table_1 (field_1)
VALUES ('A')
INSERT INTO table_1 (field_1)
VALUES ('B')
INSERT INTO table_1 (field_1)
VALUES ('C')
INSERT INTO table_1 (field_1)
VALUES ('D')
COMMIT
SELECT * FROM table_1
-- Running the code below will create and start
-- a file named query.sql which will contain the query below,
-- which will produce the results below that:
-- query that will be created:
-- SELECT MAX(DECODE(ROWNUM,1,field_1,NULL))
-- ||MAX(DECODE(ROWNUM,2,field_1,NULL))
-- ||MAX(DECODE(ROWNUM,3,field_1,NULL))
-- ||MAX(DECODE(ROWNUM,4,field_1,NULL))
-- FROM table_1 GROUP BY NULL;
-- results that will be produced:
-- ABCD
-- Notice that in this example,
-- there are only four values concatenated
-- because there are only four rows in the table.
-- If there were more rows, it would concatenate more values.
-- The number of concatenated values
-- is dependent upon the number of rows.
-- The following dynamic sql uses a single query,
-- which produces and executes a single query,
-- whose number of concatenated values is dependent
-- upon the number of rows in the table.
-- Because the echo is set off in the first line,
-- you won't see this code when you run it,
-- just the query that it creates.
SET ECHO OFF FEEDBACK OFF HEADING OFF PAGESIZE 0 VERIFY OFF
SPOOL query.sql
-- This is the start of the single query:
SELECT text
FROM (SELECT 1 AS orderby,
'SELECT MAX(DECODE(ROWNUM,1,field_1,NULL))' AS text
FROM DUAL
UNION
-- This section is the part that dynamically creates
-- one additional concatenated value
-- for each additional row after the first row.
-- This is just a subquery within the single query.
SELECT rn AS orderby,
'||MAX(DECODE(ROWNUM,'||rn||',field_1,NULL))' AS text
FROM (SELECT ROWNUM rn
FROM table_1)
WHERE rn > 1
UNION
SELECT COUNT (*) + 1 AS orderby,
'FROM table_1 GROUP BY NULL;' AS text
FROM table_1)
ORDER BY orderby;
-- This is the end of the single query.
SPOOL OFF
START query
SET ECHO ON
-- If you want to see the file containing
-- the single query that was created, then just:
-- SQL> EDIT query.sql
Similar Messages
-
Single row from this query without create a group by
Can I have a single row from this query without create a group by on tipo (TIPO can have only 2 value (A,D)
SELECT
CASE TIPO
WHEN 'D' THEN SUM(IMPORTO) ELSE 0 END DIMPORTO,
CASE TIPO
WHEN 'A' THEN SUM(IMPORTO) ELSE 0 END AIMPORTO
FROM MGIORNALE
WHERE K_CONTO = '100001' --CONTO
AND DECODE(T_MOVIM,'MRAP',TO_DATE('31/12/'||to_char(a_competenza),'DD/MM/YYYY'),DATA_RG)
-- BETWEEN DATAA AND DATAB
BETWEEN '01/01/2006' AND '31/12/2006'
--GROUP BY TIPO
--AND TIPO = COL_conto
Thanks in advanceIs like this?
sum (CASE TIPO
WHEN 'D' THEN IMPORTO ELSE 0 END) DIMPORTO, -
Updating, Adding, or Deleting rows from a query
So, I've got this page that originally was made of four
different forms. It worked great. But, then the client asked that I
"idiot proof" the page.
Originally, I had a form that enclosed a one-line table (with
Add & Clear buttons on the end) that took seven fields and
"added" a new record to the "tbljob" table.
That was followed with another form that created a table from
the results of a cfquery and listed all the rows from tbljob (with
Update/Delete buttons on the end of each row).
This worked fine when it was two separate forms. Now, I'm
trying to use only one "form" while displaying the two tables. The
buttons are now done with Javascript (so there are dialog boxes).
The problem is that I am getting a CF error message because the
insert, update, and delete commands are trying to pass the contents
of the fields as comma-delimited lists rather than the single data
item that is actually in each field. I am passing a hidden field
with each row that contains the "job_id".
I know the problem is that I'm not identifying each row as
being unique. I guess it's like I'm passing an "array" of data
rather than just a "row".
Basically, I just want to be able to display a blank row for
adding records followed by multiple rows from a query. The blank
row needs to have "Add" and "Cancel" buttons at the end and the
multi-row part has to have "Update" and "Delete" buttons on the end
of each row and manage the appropriate records.
It's got me stumped. TIA.What you can do is try using <cfloop> to insert, update
and delete your information.
For instance deleting the information try this.
<!---- Delete Jobs---->
<cfloop index="JobIDs" list="#Job_ID#" delimiters=",">
<cfquery name="delteall" datasource="dbsource">
DELETE
FROM table
Where job_Id = #JobIDs#
</cfquery>
</cfloop>
Do the same for your inserting and updating.
Because what CF see is job_id = 1,2,3,4,5,6,7,8,9
SO you are looping over a list = #job_id# and delimiter is "
, " and we are calling the index JobIDs. JobIDs are the values - 1
2 3 4 5 6 ....
I hope this helps. As for the displaying of the images, use
if then statements:
<cfif isdefined("edittable") and edittable eq '"y">
Then display the query and outputs for the editing options
<cfelseif isdefined("deletetable") and addtable eq "y">
The dispaly the query and outputs for adding options
<cfelse>
Then display the query for outputing the delete options
</cfif>
So your link will have soemthing of this sort <a
href="samepage.cfm?deletetable=y">Add Table</a>
Hope this helps,
Sevor Klu -
Removing a row from SQL query results when there is a duplicate hostname
I have a query created for a software usage report in SCCM. When there are multiple versions of the same software (Acrobat) installed on the same machine, I will receive duplicate results for the same machine. For example, it will come back with Acrobat
9 and another Acrobat 10 for HOSTNAME1. However, only Acrobat 10 has a usage count. Is it possible to delete the row for Acrobat that has a software usage count of "0/null" if there is another Acrobat results showing up that actually has a usage
count? Let me know if I need to clarify. Any suggestions would be appreciated.It is more complicated than doing just "Where usage count >0 and usage is not NULL"
because I still want results that have a 0 usage count. I just don't want to have duplicate machines show up for the same software IF one of them returns a usage count of 0.
SELECT DISTINCT
abc.SECTOR
,abc.BA
,abc.SITE
,abc.HOSTNAME as 'Name0'
,rs.ResourceID
,CASE
WHEN mf.OriginalFileName = 'dwrcc.exe' THEN 'DameWare'
WHEN mf.OriginalFileName = 'matlab.exe' THEN 'MathWorks'
WHEN mf.OriginalFileName IN ('encoder.exe','expressionweb.exe','exprwd.exe','mappoint.exe','winproj.exe','visio.exe','devenv.exe','VBExpress.exe','VCExpress.exe','VCSExpress.exe','VWDExpress.exe','excel.exe','groove.exe','infopath.exe','msaccess.exe','mspub.exe','onenote.exe','outlook.exe','powerpnt.exe','winword.exe','communicator.exe')
THEN 'Microsoft'
WHEN mf.OriginalFileName IN ('acrobat.exe','Acrobat Elements.exe','AfterFX.exe','Audition.Exe','Adobe Audition.Exe','AdobeCaptivate.exe','CFReportBuilder.exe','Coldfusion.Exe','Contribute.exe','director.exe','Projector.exe','dreamweaver.exe','Adobe
Encore.exe','Adobe Encore Dvd.Exe','Encoredvd.Exe','Fireworks.exe','FlashBuilder4.exe','flash.exe','Flex Builder.exe','FlexBuilder.exe','Framemaker.Exe','framemaker+sgml.exe','illustrator.exe','HomeSite+.exe','homesite4.exe','homesite45.exe','Homesite5.exe','InDesign.exe','Lightroom.exe','Adobe
OnLocation.exe','Pm65.Exe','Pm70.Exe','pm.exe','pm4.exe','pm5.exe','pm6.exe','photoshop.exe','Photosle.exe','Photoshopelementsorganizer.Exe','Photoshopelementseditor.Exe','photoshp.exe','Lightroom.exe','Adobe Premiere Elements.Exe','Adobe Premiere Elements
8.0.Exe','Adobe Premiere Elements 10.Exe','Adobe Premiere Elements 9.Exe','Adobe Premiere Elements 7.0.exe','Premiere.Exe','Adobe Premiere Pro.Exe','Adobe-Pr-Vc.Exe','Robohelp.Exe','robodemo.exe','roboinfo.exe','Adobe Soundbooth CS5.exe','Adobe Soundbooth
CS4.exe','Adobe Soundbooth CS3.exe','Adobe Media Encoder.exe','speedgrade.exe','adobe prelude.exe') THEN 'Adobe'
ELSE 'OTHER'
END as 'Publisher'
,(CASE mf.OriginalFileName
WHEN 'acrobat.exe' THEN 'Acrobat'
WHEN 'Acrobat Elements.exe' THEN 'Acrobat Elements'
WHEN 'AfterFX.exe' THEN 'After Effects'
WHEN 'Audition.exe' THEN 'Audition'
WHEN 'Adobe Audition.exe' THEN 'Audition'
WHEN 'AdobeCaptivate.exe' THEN 'Captivate'
WHEN 'CFReportBuilder.exe' THEN 'Coldfusion Builder'
WHEN 'Coldfusion.exe' THEN 'Coldfusion Standard'
WHEN 'Contribute.exe' THEN 'Contribute'
WHEN 'dwrcc.exe' THEN 'DameWare Mini Remote Control'
WHEN 'director.exe' THEN 'Director'
WHEN 'Projector.exe' THEN 'Director'
WHEN 'dreamweaver.exe' THEN 'Dreamweaver'
WHEN 'Adobe Encore.exe' THEN 'Encore'
WHEN 'Adobe Encore Dvd.exe' THEN 'Encore'
WHEN 'Encoredvd.exe' THEN 'Encore'
WHEN 'encoder.exe' THEN 'Expression'
WHEN 'expressionweb.exe' THEN 'Expression'
WHEN 'exprwd.exe' THEN 'Expression'
WHEN 'Fireworks.exe' THEN 'Fireworks'
WHEN 'FlashBuilder4.exe' THEN 'Flash Builder'
WHEN 'flash.exe' THEN 'Flash Pro'
WHEN 'Flex Builder.exe' THEN 'FlexBuilder'
WHEN 'FlexBuilder.exe' THEN 'FlexBuilder'
WHEN 'Framemaker.exe' THEN 'FrameMaker'
WHEN 'framemaker+sgml.exe' THEN 'FrameMaker'
WHEN 'HomeSite+.exe' THEN 'Homesite'
WHEN 'homesite4.exe' THEN 'Homesite'
WHEN 'homesite45.exe' THEN 'Homesite'
WHEN 'Homesite5.exe' THEN 'Homesite'
WHEN 'illustrator.exe' THEN 'Illustrator'
WHEN 'InDesign.exe' THEN 'InDesign'
WHEN 'Lightroom.exe' THEN 'Lightroom'
WHEN 'mappoint.exe' THEN 'MapPoint'
WHEN 'Adobe Media Encoder.exe' THEN 'Media Encoder'
WHEN 'Adobe OnLocation.exe' THEN 'OnLocation'
WHEN 'Pm65.exe' THEN 'PageMaker'
WHEN 'Pm70.exe' THEN 'PageMaker'
WHEN 'pm.exe' THEN 'PageMaker'
WHEN 'pm4.exe' THEN 'PageMaker'
WHEN 'pm5.exe' THEN 'PageMaker'
WHEN 'pm6.exe' THEN 'PageMaker'
WHEN 'photoshop.exe' THEN 'Photoshop'
WHEN 'Photosle.exe' THEN 'Photoshop'
WHEN 'Photoshopelementsorganizer.exe' THEN 'Photoshop Elements'
WHEN 'Photoshopelementseditor.exe' THEN 'Photoshop Elements'
WHEN 'photoshp.exe' THEN 'Photoshop Elements'
WHEN 'Lightroom.exe' THEN 'Photoshop Lightroom'
WHEN 'adobe prelude.exe' THEN 'Prelude'
WHEN 'Adobe Premiere Elements.exe' THEN 'Premiere Elements'
WHEN 'Adobe Premiere Elements 8.0.exe' THEN 'Premiere Elements'
WHEN 'Adobe Premiere Elements 10.exe' THEN 'Premiere Elements'
WHEN 'Adobe Premiere Elements 9.exe' THEN 'Premiere Elements'
WHEN 'Adobe Premiere Elements 7.0.exe' THEN 'Premiere Elements'
WHEN 'Premiere.exe' THEN 'Premiere Pro'
WHEN 'Adobe Premiere Pro.exe' THEN 'Premiere Pro'
WHEN 'Adobe-Pr-Vc.exe' THEN 'Presenter'
WHEN 'winproj.exe' THEN 'Project'
WHEN 'Robohelp.exe' THEN 'RoboHelp'
WHEN 'robodemo.exe' THEN 'RoboHelp'
WHEN 'roboinfo.exe' THEN 'RoboHelp'
WHEN 'Adobe Soundbooth CS5.exe' THEN 'Soundbooth'
WHEN 'Adobe Soundbooth CS4.exe' THEN 'Soundbooth'
WHEN 'Adobe Soundbooth CS3.exe' THEN 'Soundbooth'
WHEN 'speedgrade.exe' THEN 'Speedgrade'
WHEN 'visio.exe' THEN 'Visio'
WHEN 'devenv.exe' THEN 'Visual Studio'
WHEN 'VBExpress.exe' THEN 'Visual Studio'
WHEN 'VCExpress.exe' THEN 'Visual Studio'
WHEN 'VCSExpress.exe' THEN 'Visual Studio'
WHEN 'VWDExpress.exe' THEN 'Visual Studio'
WHEN 'WinWord.exe' THEN 'Word'
WHEN 'matlab.exe' THEN 'MATLAB'
ELSE mf.OriginalFileName
END) as 'ProductName'
,mf.OriginalFileName
,sf.FileDescription
,CASE
WHEN sf.FilePath like '%acrobat%' and sf.FileVersion != '' THEN left(sf.FileVersion,patindex('%.%',sf.FileVersion)-1)
ELSE sf.FileVersion
END AS 'FileVersion'
,sf.FilePath
,mf.MeteredFileID
,ISNULL(mus.UsageTime, '') as 'USAGETIME'
,ISNULL(mus.UsageCount, '') as 'USAGECOUNT'
,mus.LastUsage
--,ISNULL(CONVERT(VARCHAR,mus.LastUsage,21),'') as 'Last Used'
,CASE
WHEN mus.LastUsage IS NULL and
sf.FilePath like '%\Program Files\Hewlett-Packard\%'
or sf.FilePath like '_:\Windows\%'
or sf.FilePath like '% old %'
or sf.FilePath like '%[_]old[_]%'
or sf.FilePath like '%backup%'
or sf.FilePath like '_:\Data\%'
or sf.FilePath like 'C:\Users\%'
or sf.FilePath like 'C:\Documents and Settings\%'
or (sf.FileName = 'acrobat.exe' and sf.FileDescription IS NULL)
THEN 'FALSE'
ELSE 'TRUE'
END as 'VALID'
,ISNULL(ui.UserName,scum.TopConsoleUser0) as 'PrimaryUser'
FROM
v_MeteredFiles mf
INNER JOIN v_GS_SoftwareFile sf on mf.MeteredFileID = sf.FileID
--LEFT JOIN v_SoftwareFile sfi on sfi.FileID = sf.FileID
LEFT JOIN v_R_System rs on sf.ResourceID = rs.ResourceID and rs.Obsolete0 = 0 and rs.Active0 = 1
LEFT JOIN v_CH_ClientSummary ch on ch.ResourceID = rs.ResourceID
INNER JOIN [CUSTOM].[dbo].[ABC_SITES] abc on rs.Name0 = abc.HOSTNAME and abc.SERV_FL = 'N'
LEFT JOIN (
SELECT ResourceID,FileID,SUM(UsageCount) as 'UsageCount',MAX(MeteredUserID) as 'UserID',SUM(UsageTime) as 'UsageTime',MAX(LastUsage) as 'LastUsage'
FROM v_MonthlyUsageSummary
GROUP BY ResourceID,FileID
) mus on mus.ResourceID = sf.ResourceID and mus.FileID = mf.MeteredFileID
LEFT JOIN v_Users ui on ui.UserID = mus.UserID
LEFT JOIN v_GS_SYSTEM_CONSOLE_USAGE_MAXGROUP scum on scum.ResourceID = rs.ResourceID
WHERE
(ch.LastActiveTime >= GETDATE()-30 or bae.LOGON_TMSP >= GETDATE()-30)
and mf.OriginalFileName != 'WinWord.exe'
--Exclude files in Recycle Bin
and sf.FilePath not like '_:\$Recycle.Bin%'
--Exclude invalid flash FileID's:
and sf.FileID not in ('216172782114109353','216172782113863960','216172782113863969','216172782114336737','216172782114337853','216172782114009539','216172782114088205','216172782114148960','216172782114088174','216172782114109319','216172782113854316','216172782114045303','216172782114103331','216172782114318673','216172782113997536','216172782114103319','216172782114035585','216172782114035580','288230376151905593','288230376152414835','288230376152326390','288230376152414762','288230376152752371','288230376152238194','288230376151864114','288230376152221470','288230376152194417','288230376152452591','288230376152433530','288230376151826881','288230376151905590','288230376151993886','288230376152142718','288230376151766967','288230376151949862','288230376151870700','288230376151805491','288230376151796019','288230376152041232','288230376152068486','288230376152330596','288230376151982279','288230376151982277','288230376152126901','288230376151864098','288230376152129697','288230376152055728','216172782113836986','288230376152068474','288230376152068500','288230376151754145','288230376152241787','216172782113974892','288230376152107352','288230376152049272','288230376152367258','288230376152014270','288230376152423348','288230376151777614','288230376152137355','288230376152699042','288230376151777252','288230376152025890','288230376152688217','216172782113850093','216172782113850201','216172782114478326','216172782114139161','216172782113976965','216172782114084839','216172782114084848','288230376151766956','288230376152068464','288230376151766948','288230376152068455','288230376151903237','288230376151857402','288230376151933218','216172782113888320','216172782113867157','216172782113798401','216172782113884867')
and sf.FileDescription not like '%PackageForTheWeb%'
and sf.FileDescription not like '%Projector%'
and sf.FileDescription not like '%Adobe Reader%'
and sf.FileDescription not like '%Netopsystems%'
and abc.SECTOR in (@Sector)
and abc.BA in (@Business_Area)
and abc.SITE in (@Site)
and (CASE mf.OriginalFileName
WHEN 'acrobat.exe' THEN 'Acrobat'
WHEN 'Acrobat Elements.exe' THEN 'Acrobat Elements'
WHEN 'AfterFX.exe' THEN 'After Effects'
WHEN 'Audition.exe' THEN 'Audition'
WHEN 'Adobe Audition.exe' THEN 'Audition'
WHEN 'AdobeCaptivate.exe' THEN 'Captivate'
WHEN 'CFReportBuilder.exe' THEN 'Coldfusion Builder'
WHEN 'Coldfusion.exe' THEN 'Coldfusion Standard'
WHEN 'Contribute.exe' THEN 'Contribute'
WHEN 'dwrcc.exe' THEN 'DameWare Mini Remote Control'
WHEN 'director.exe' THEN 'Director'
WHEN 'Projector.exe' THEN 'Director'
WHEN 'dreamweaver.exe' THEN 'Dreamweaver'
WHEN 'Adobe Encore.exe' THEN 'Encore'
WHEN 'Adobe Encore Dvd.exe' THEN 'Encore'
WHEN 'Encoredvd.exe' THEN 'Encore'
WHEN 'encoder.exe' THEN 'Expression'
WHEN 'expressionweb.exe' THEN 'Expression'
WHEN 'exprwd.exe' THEN 'Expression'
WHEN 'Fireworks.exe' THEN 'Fireworks'
WHEN 'FlashBuilder4.exe' THEN 'Flash Builder'
WHEN 'flash.exe' THEN 'Flash Pro'
WHEN 'Flex Builder.exe' THEN 'FlexBuilder'
WHEN 'FlexBuilder.exe' THEN 'FlexBuilder'
WHEN 'Framemaker.exe' THEN 'FrameMaker'
WHEN 'framemaker+sgml.exe' THEN 'FrameMaker'
WHEN 'HomeSite+.exe' THEN 'Homesite'
WHEN 'homesite4.exe' THEN 'Homesite'
WHEN 'homesite45.exe' THEN 'Homesite'
WHEN 'Homesite5.exe' THEN 'Homesite'
WHEN 'illustrator.exe' THEN 'Illustrator'
WHEN 'InDesign.exe' THEN 'InDesign'
WHEN 'Lightroom.exe' THEN 'Lightroom'
WHEN 'mappoint.exe' THEN 'MapPoint'
WHEN 'Adobe Media Encoder.exe' THEN 'Media Encoder'
WHEN 'Adobe OnLocation.exe' THEN 'OnLocation'
WHEN 'Pm65.exe' THEN 'PageMaker'
WHEN 'Pm70.exe' THEN 'PageMaker'
WHEN 'pm.exe' THEN 'PageMaker'
WHEN 'pm4.exe' THEN 'PageMaker'
WHEN 'pm5.exe' THEN 'PageMaker'
WHEN 'pm6.exe' THEN 'PageMaker'
WHEN 'photoshop.exe' THEN 'Photoshop'
WHEN 'Photosle.exe' THEN 'Photoshop'
WHEN 'Photoshopelementsorganizer.exe' THEN 'Photoshop Elements'
WHEN 'Photoshopelementseditor.exe' THEN 'Photoshop Elements'
WHEN 'photoshp.exe' THEN 'Photoshop Elements'
WHEN 'Lightroom.exe' THEN 'Photoshop Lightroom'
WHEN 'adobe prelude.exe' THEN 'Prelude'
WHEN 'Adobe Premiere Elements.exe' THEN 'Premiere Elements'
WHEN 'Adobe Premiere Elements 8.0.exe' THEN 'Premiere Elements'
WHEN 'Adobe Premiere Elements 10.exe' THEN 'Premiere Elements'
WHEN 'Adobe Premiere Elements 9.exe' THEN 'Premiere Elements'
WHEN 'Adobe Premiere Elements 7.0.exe' THEN 'Premiere Elements'
WHEN 'Premiere.exe' THEN 'Premiere Pro'
WHEN 'Adobe Premiere Pro.exe' THEN 'Premiere Pro'
WHEN 'Adobe-Pr-Vc.exe' THEN 'Presenter'
WHEN 'winproj.exe' THEN 'Project'
WHEN 'Robohelp.exe' THEN 'RoboHelp'
WHEN 'robodemo.exe' THEN 'RoboHelp'
WHEN 'roboinfo.exe' THEN 'RoboHelp'
WHEN 'Adobe Soundbooth CS5.exe' THEN 'Soundbooth'
WHEN 'Adobe Soundbooth CS4.exe' THEN 'Soundbooth'
WHEN 'Adobe Soundbooth CS3.exe' THEN 'Soundbooth'
WHEN 'speedgrade.exe' THEN 'Speedgrade'
WHEN 'visio.exe' THEN 'Visio'
WHEN 'devenv.exe' THEN 'Visual Studio'
WHEN 'VBExpress.exe' THEN 'Visual Studio'
WHEN 'VCExpress.exe' THEN 'Visual Studio'
WHEN 'VCSExpress.exe' THEN 'Visual Studio'
WHEN 'VWDExpress.exe' THEN 'Visual Studio'
WHEN 'WinWord.exe' THEN 'Word'
WHEN 'matlab.exe' THEN 'Matlab'
ELSE mf.OriginalFileName
END) IN (@MeteredProduct)
ORDER BY
abc.SECTOR
,abc.BA
,abc.SITE
,abc.HOSTNAME -
Need different rows from single query based on condition
Hi,
I have a table with 100 rows that holds employees and their roles.
I need to write a SQL(not a PL/SQL block) as below
1. When employee with role 'VP' logs in, the query should return all the 100 rows.
2. When employee with role 'MGR' logs in, the query should return only those rows whose MGR is the logged in employee.
3. When employee with role 'SALE_EXEC' logs in, it should return single rows corresponding to this SALE_EXEC.
My requirement here is to get these outputs from a single query.
Can anyone please help me with this.
Thanks,
Vivek.use vpd
New Policy Groups
When adding the policy to a table, view, or synonym, you can use the DBMS_RLS.ADD_GROUPED_POLICY interface to specify the group to which the policy belongs. To specify which policies will be effective, you add a driving context using the DBMS_RLS.ADD_POLICY_CONTEXT interface. If the driving context returns an unknown policy group, then an error is returned.
If the driving context is not defined, then all policies are executed. Likewise, if the driving context is NULL, then policies from all policy groups are enforced. In this way, an application accessing the data cannot bypass the security setup module (which sets up application context) to avoid any applicable policies.
You can apply multiple driving contexts to the same table, view, or synonym, and each of them will be processed individually. In this way, you can configure multiple active sets of policies to be enforced.
Consider, for example, a hosting company that hosts Benefits and Financial applications, which share some database objects. Both applications are striped for hosting using a SUBSCRIBER policy in the SYS_DEFAULT policy group. Data access is partitioned first by subscriber ID, then by whether the user is accessing the Benefits or Financial applications (determined by a driving context). Suppose that Company A, which uses the hosting services, wants to apply a custom policy which relates only to its own data access. You could add an additional driving context (such as COMPANY A SPECIAL) to ensure that the additional, special policy group is applied for data access for Company A only. You would not apply this under the SUBSCRIBER policy, because the policy relates only to Company A, and it is more efficient to segregate the basic hosting policy from other policies.
How to Implement Policy Groups
To create policy groups, the administrator must do two things:
Set up a driving context to identify the effective policy group.
Add policies to policy groups as required.
The following example shows how to perform these tasks.
Note:
You need to set up the following data structures for the examples in this section to work:
DROP USER finance CASCADE;
CREATE USER finance IDENTIFIED BY welcome2;
GRANT RESOURCE TO apps;
DROP TABLE apps.benefit;
CREATE TABLE apps.benefit (c NUMBER);
Step 1: Set Up a Driving Context
Begin by creating a namespace for the driving context. For example:
CREATE CONTEXT appsctx USING apps.apps_security_init;
Create the package that administers the driving context. For example:
CREATE OR REPLACE PACKAGE apps.apps_security_init IS
PROCEDURE setctx (policy_group VARCHAR2);
END;
CREATE OR REPLACE PACKAGE BODY apps.apps_security_init AS
PROCEDURE setctx ( policy_group varchar2 ) IS
BEGIN
REM Do some checking to determine the current application.
REM You can check the proxy if using the proxy authentication feature.
REM Then set the context to indicate the current application.
DBMS_SESSION.SET_CONTEXT('APPSCTX','ACTIVE_APPS', policy_group);
END;
END;
Define the driving context for the table APPS.BENEFIT.
BEGIN
DBMS_RLS.ADD_POLICY_CONTEXT('apps','benefit','APPSCTX','ACTIVE_APPS');
END;
Step 2: Add a Policy to the Default Policy Group.
Create a security function to return a predicate to divide the data by company.
CREATE OR REPLACE FUNCTION by_company (sch varchar2, tab varchar2)
RETURN VARCHAR2 AS
BEGIN
RETURN 'COMPANY = SYS_CONTEXT(''ID'',''MY_COMPANY'')';
END;
Because policies in SYS_DEFAULT are always executed (except for SYS, or users with the EXEMPT ACCESS POLICY system privilege), this security policy (named SECURITY_BY_COMPANY), will always be enforced regardless of the application running. This achieves the universal security requirement on the table: namely, that each company should see its own data regardless of the application that is running. The function APPS.APPS_SECURITY_INIT.BY_COMPANY returns the predicate to make sure that users can only see data related to their own company:
BEGIN
DBMS_RLS.ADD_GROUPED_POLICY('apps','benefit','SYS_DEFAULT',
'security_by_company',
'apps','by_company');
END;
Step 3: Add a Policy to the HR Policy Group
First, create the HR group:
CREATE OR REPLACE FUNCTION hr.security_policy
RETURN VARCHAR2
AS
BEGIN
RETURN 'SYS_CONTEXT(''ID'',''TITLE'') = ''MANAGER'' ';
END;
The following creates the policy group and adds a policy named HR_SECURITY to the HR policy group. The function HR.SECURITY_POLICY returns the predicate to enforce security on the APPS.BENEFIT table:
BEGIN
DBMS_RLS.CREATE_POLICY_GROUP('apps','benefit','HR');
DBMS_RLS.ADD_GROUPED_POLICY('apps','benefit','HR',
'hr_security','hr','security_policy');
END;
Step 4: Add a Policy to the FINANCE Policy Group
Create the FINANCE policy:
CREATE OR REPLACE FUNCTION finance.security_policy
RETURN VARCHAR2
AS
BEGIN
RETURN ('SYS_CONTEXT(''ID'',''DEPT'') = ''FINANCE'' ');
END;
Create a policy group named FINANCE and add the FINANCE policy to the FINANCE group:
BEGIN
DBMS_RLS.CREATE_POLICY_GROUP('apps','benefit','FINANCE');
DBMS_RLS.ADD_GROUPED_POLICY('apps','benefit','FINANCE',
'finance_security','finance', 'security_policy');
END;
As a result, when the database is accessed, the application initializes the driving context after authentication. For example, with the HR application:
execute apps.security_init.setctx('HR');
Validating the Application Used to Connect to the Database
The package implementing the driving context must correctly validate the application that is being used to connect to the database. Although the database always checks the call stack to ensure that the package implementing the driving context sets context attributes, inadequate validation can still occur within the package.
For example, in applications where database users or enterprise users are known to the database, the user needs the EXECUTE privilege on the package that sets the driving context. Consider a user who knows that:
The BENEFITS application allows more liberal access than the HR application
The setctx procedure (which sets the correct policy group within the driving context) does not perform any validation to determine which application is actually connecting. That is, the procedure does not check either the IP address of the incoming connection (for a three-tier system) or the proxy_user attribute of the user session.
Such a user could pass to the driving context package an argument setting the context to the more liberal BENEFITS policy group, and then access the HR application instead. Because the setctx does no further validation of the application, this user bypasses the normally more restrictive HR security policy.
By contrast, if you implement proxy authentication with VPD, then you can determine the identity of the middle tier (and the application) that is actually connecting to the database on behalf of a user. In this way, the correct policy will be applied for each application to mediate data access.
For example, a developer using the proxy authentication feature could determine that the application (the middle tier) connecting to the database is HRAPPSERVER. The package that implements the driving context can thus verify whether the proxy_user in the user session is HRAPPSERVER. If so, then it can set the driving context to use the HR policy group. If proxy_user is not HRAPPSERVER, then it can disallow access.
In this case, when the following query is executed
SELECT * FROM APPS.BENEFIT;
Oracle Database picks up policies from the default policy group (SYS_DEFAULT) and active namespace HR. The query is internally rewritten as follows:
SELECT * FROM APPS.BENEFIT WHERE COMPANY = SYS_CONTEXT('ID','MY_COMPANY') and SYS_CONTEXT('ID','TITLE') = 'MANAGER';
How to Add a Policy to a Table, View, or Synonym
The DBMS_RLS package enables you to administer security policies by using its procedures for adding, enabling, refreshing, or dropping policies, policy groups, or application contexts. You need to specify the table, view, or synonym to which you are adding a policy, as well as the data pertinent to that policy, such as the policy name. Such data also includes names for the policy group and the function implementing the policy. You can also specify the types of statements the policy controls (SELECT, INSERT, UPDATE, DELETE, CREATE INDEX, or ALTER INDEX).
for more you can refer to
http://download-west.oracle.com/docs/cd/B19306_01/network.102/b14266/apdvcntx.htm -
Get multiple rows from mysql query in NetBeans
Hi, I am working on a project in NetBeans 6.I have a checkboxlist, and I have a variable in which I save the selected values of the checkboxlist.Now, I want to make a query that will get the rows of the rowset that have the same id as the selected values.for example, I have a checkboxlist that has the following values: Helen, Maria, Anna.The user checks the first two, so I have a variable String[] "checked" that has in it the data 1,2.Now, I have a rowset that has the following query:
SELECT ALL person.age
FROM person
WHERE person.id=? or something like this.I want the parameters to have the values (1,2) so that the rowset has the results of the ages of the two first rows.How do I accomplish that?I am assuming that with one "?" it can't be done because I need multiple parameters. Will something like this work: WHERE person.id IN something,but what will something be?christomar wrote:
I have a rowset that has the following query:
SELECT ALL person.age
FROM person
WHERE person.id=? or something like this.I want the parameters to have the values (1,2) so that the rowset has the results of the ages of the two first rows.How do I accomplish that?Use a PreparedStatement. You probably first need to read the Sun JDBC Tutorial before you do anything.
I am assuming that with one "?" it can't be done because I need multiple parameters. I've seen people use up to 76 parameters so yes it can be done, it will look like this:
Will something like this work: WHERE person.id IN something,Yes, you can submit any SQL you want as long as your db supports it (all support ANSI i believe)
but what will something be?something in that context would be a list/set of data, but you're getting ahead of yourself I think. do the tutorial and look at some code -
I have a form based on a table.
Is it possible to display the number of rows return by the query - something like row 1 of 12I know it has been a long time since the original question, but I also required this functionality . This code will display "No match found." OR "Record n of M matching records" after a form has been queried.
-- Put this code in the "after processing the form" section
-- Edit the value of "_tablename" to match the name of the table on which the form was based.
declare
"_tablename" varchar2(255) := '*** DATABASE_TABLE_NAME ***';
"_curr_in_set" integer;
"_first_rec" integer;
"_last_rec" integer;
"_select" varchar2(32767);
"_where" varchar2(32767);
"_c1" "_ref_cursor";
begin
"_curr_in_set" := p_session.get_value_as_number(
p_block_name => 'DEFAULT',
p_attribute_name => '_CURR_IN_SET',
p_index => 1
"_first_rec":=p_session.get_value_as_number(
p_block_name => 'DEFAULT',
p_attribute_name => '_FIRST_REC',
p_index => 1
"_where":=p_session.get_value_as_varchar2(
p_block_name => 'DEFAULT',
p_attribute_name => '_WHERE_CLAUSE',
p_index => 1
if ("_curr_in_set" is not null) then
if ("_curr_in_set" = 0) then
htp.p('No match found.');
else
"_select" := 'SELECT COUNT(*) FROM '
|| "_tablename" || ' ' || "_where";
open "_c1" for "_select";
fetch "_c1" into "_last_rec";
htp.p('Record '
|| to_char("_curr_in_set"+"_first_rec"-1)
||' of '
||to_char("_last_rec")
||' matching records.');
end if;
end if;
end; -
Want to delete Rows from SAP Query which have u20180u2019 or blank values
Hi Experts,
I have made one sap-query, in that I have added some additional fields, after that I am getting some blank or u20180u2019 values in some rows, can anyone tell me how to delete those rows which have u20180u2019 or blank values.
Regards
Mahadev RoyHi mahadev
You must be fetching data from SQ02 in some internal table.Delete values from that internal table.
Also as you are fetching records from SQ02 then in the select statement you can put this condition of '0' and blank
so that you will get appropriate result.
Thanks
Khushboo -
HOW TO EXECUTE A STORE PROCEDURE THAT RETURN MULTIPLE ROWS FROM A QUERY
I NEED TO CREATE AND USE A STORE PROCEDURE THAT IS GOING TO DO A SELECT STATEMENT AN THE RESULT OF THE SELECT STATEMENT IS RETURN IN SOME WAY TO THE REQUESTER.
THIS CALL IS MADE BY AN EXTERNAL LANGUAGE, NOT PL/SQL OR FORMS APPLICATION. USING FOR EXAMPLE ODBC AND VISUAL BASIC. WHAT I NEED TO DO IS ADD A DATA ACCESS LAYER TO MY APPLICATION AND I ALREADY HAVE IT DONE FOR MS SQL SERVER, BUT I NEED THE SAME FUNCTIONALITY ACCESSING AN ORACLE DATABASE.
FLOW:
1. VB CREATE A ODBC CONNECTION TO A ORACLE DATABASE
2. VB EXECUTE A STORE PROCEDURE
3. THE STORE PROCEDURE RETURNS TO THE VB APPLICATION THE RESULT OF THE QUERY THAT IS INSIDE OF THE STORE PROCEDURE.(I.E. THE STORE PROCEDURE IS A BASIC SELECT, NOTHING COMPLEX)
4. VB DISPLAY THE RESULT IN A GRID
FOR SURE I CAN DO THE SELECT DIRECTLY TO ORACLE, BUT FOR PERFORMANCE REASONS AND SCALABILITY, I'LL LIKE IT TO DO IT USING A STORE PROCUDURES
IS THIS POSIBLE?, HOW?
THANKSCertainly, it's possible. First, define a stored procedure that includes an OUT parameter which is a REF CURSOR. Then, call the stored procedure via ODBC omitting the OUT parameter from the list of parameters. IT will automatically be returned as a result set. Syntax for both is below...
CREATE PROCEDURE foo (inParam in varchar2, resultSet OUT REF CURSOR )
In ODBC:
{call foo( 'someData' )}
Justin -
How to extract multiple rows from a query and how to populate it in form.
hi all,
i want to populate multiple rows fetched from a cursor into form.
i write this procedur.
PROCEDURE populate_q (v_t_no IN number) IS
cursor ext_q is
select test_question.no, q_no, text, ans1
from test_question , question
where test_question.no = v_t_no;
BEGIN
for ext_rec in ext_q loop
:take_detail.q_no := ext_rec.q_no;
:take_detail.question := ext_rec.text;
EXIT WHEN ext_q%notfound;
end loop;
END;
and call this WHEN-NEW-BLOCK-INSTANCE trigger.
this don't return all the rows only the lost one is populated
and shown in form.
thanks
Muhammad Nadeem
Mardan (pakistan)
[email protected]Hi,
look for the next_record built-in. Your cusror only addresses the current row, but you want to create new rows as you go
Frank -
Selecting only one row from a query
Hi,
I am using database version 10.2.0.4.0
I have 2 tables:
artist(artistid, artistname, titleid)
trans(transid, datesold, salesprice, titleid, artistid)
This is what i used and got the below results.
SELECT max(worksold) AS mostworksold
FROM (
SELECT artistname, COUNT(t.artistid) AS worksold
FROM table.artist a, table.trans t
WHERE a.artistid = t.artistid
GROUP BY artistname
MOSTWORKSOLD
12
However I also want to show the artist name who sold the most work. So i added artist name in the select, but the result came out very different.
SELECT artistname, max(worksold) AS mostworksold
FROM (
SELECT artistname, COUNT(t.artistid) AS worksold
FROM table.artist a, table.trans t
WHERE a.artistid = t.artistid
GROUP BY artistname
group by artistname;
ARTISTNAME MOSTWORKSOLD
John 3
Mary 4
Alvin 9
Trevor 5
Jess 12
What should I do to make it show only this?
ARTISTNAME MOSTWORKSOLD
Jess 12
Regards,
Keith
Edited by: 963214 on Oct 5, 2012 10:12 AM
Edited by: 963214 on Oct 5, 2012 10:40 AMtry this... hope this helps...
with xx as(
select '1' as aid,'john' as anm from dual union all
select '2' as aid,'mary' as anm from dual union all
select '3' as aid,'alvin' as anm from dual union all
select '4' as aid,'trevor' as anm from dual union all
select '5' as aid,'jess' as anm from dual
), yy as(
select '1' aid from dual union all
select '2' aid from dual union all
select '2' aid from dual union all
select '3' aid from dual union all
select '3' aid from dual union all
select '3' aid from dual union all
select '4' aid from dual union all
select '4' aid from dual union all
select '4' aid from dual union all
select '4' aid from dual union all
select '4' aid from dual union all
select '5' aid from dual
select x.* from
(SELECT a.anm as nm, COUNT(t.aid) AS worksold
FROM xx a, yy t
WHERE a.aid = t.aid
GROUP BY anm
order by worksold desc) x
where rownum = 1; gives
trevor 5In 2 ^nd^ table, i've considered only 1 column which is actually used. Rest columns are unessential.
Ranit B.
Edited by: ranit B on Oct 6, 2012 12:20 AM -
Storing individual resutls(rows) from a query which is run every minute
Is there a way i can issue a query like
select item_desc from item_dtl where track_code='UNPROCESSED';
every 1 minute and permanantly store the results of this query to a table.
How would you achieve this?Upon every refresh of a materialized view, is there a way i can permanantly store these results like a table????
Sorry, but I'm not sure what you are trying to accomplish.
You can schedule a periodic refresh of a materialized view and it will reflect whatever has changed in the base table(s).
You'll need to post a lot more detail on what this is for. -
Need to remove duplicate rows from distinct query
Hello,
I have the following query:
SELECT tiab.abnr abnr, tiab.namn namn, (CAST(tiab.GATUNR||' '||tiab.gata AS VARCHAR2(254))) ADR, tiab.boxpnr boxpnr, tiab.boxort boxort,
(CAST(tiab.RIKTNRDISPLAY AS VARCHAR2(254))) RIKTNR, (CAST(tiab.TELNRDISPLAY AS VARCHAR2(254))) TELNR,
DECODE((select count(tior.tigilopnr) from tis.tior where abnr = tiab.abnr and inplnr IN (3797886)),0 ,NULL , 1, tior.tigilopnr, 'N/A') tigilopnr
FROM tis.tiab
JOIN tis.tior on tiab.abnr = tior.abnr
WHERE tior.inplnr IN (3797886)
ORDER BY tiab.ABNR )
ORDER BY abnr;
It returns the following:
14684940 Pizza Station Inc The Lafayette 26170 St Marys 304 684-2411
15123161 Chris Test 554 Easy St n 43333 Columbus 614 555-5555
15123162 Chris Test2 5556 Easy St 43333 Columbus 614 555-5151 2553304 --> keep this one
15123162 Chris Test2 5556 Easy St 43333 Columbus 614 555-5151 -- not show this
I have tried several different things as well as looking through the forums but have not found anything that will only give me unique records based only on the first column. This query works fine as long as there
are not 2 records returned with column1 being identical.
Final results should look like this:
14684940 Pizza Station Inc The Lafayette 26170 St Marys 304 684-2411
15123161 Chris Test 554 Easy St n 43333 Columbus 614 555-5555
15123162 Chris Test2 5556 Easy St 43333 Columbus 614 555-5151 2553304
Thanks in advance for the assistance.Hello,
Try:
SELECT abnr, namn, ADR, boxpnr, boxort,RIKTNR, TELNR,tigilopnr
FROM (
SELECT tiab.abnr abnr, tiab.namn namn, (CAST(tiab.GATUNR||' '||tiab.gata AS VARCHAR2(254))) ADR, tiab.boxpnr boxpnr, tiab.boxort boxort,
(CAST(tiab.RIKTNRDISPLAY AS VARCHAR2(254))) RIKTNR, (CAST(tiab.TELNRDISPLAY AS VARCHAR2(254))) TELNR,
DECODE((select count(tior.tigilopnr) from tis.tior where abnr = tiab.abnr and inplnr IN (3797886)),0 ,NULL , 1, tior.tigilopnr, 'N/A') tigilopnr,
ROW_NUMBER () OVER (PARTITION BY tiab.abnr ORDER BY (CAST(tiab.TELNRDISPLAY AS VARCHAR2(254))) NULLS LAST) row_num
FROM tis.tiab
JOIN tis.tior on tiab.abnr = tior.abnr
WHERE tior.inplnr IN (3797886))
WHERE row_num <= 1
ORDER BY abnr;Or, with your current query:
SELECT abnr, namn, ADR, boxpnr, boxort,RIKTNR, TELNR,tigilopnr
FROM (
SELECT distinct tiab.abnr abnr, tiab.namn namn, (CAST(tiab.GATUNR||' '||tiab.gata AS VARCHAR2(254))) ADR, tiab.boxpnr boxpnr, tiab.boxort boxort,
(CAST(tiab.RIKTNRDISPLAY AS VARCHAR2(254))) RIKTNR, (CAST(tiab.TELNRDISPLAY AS VARCHAR2(254))) TELNR,
DECODE((select count(tior.tigilopnr) from tis.tior where abnr = tiab.abnr and inplnr IN (3797886)),0 ,NULL , 1, tior.tigilopnr, 'N/A') tigilopnr,
ROW_NUMBER () OVER (PARTITION BY tiab.abnr ORDER BY (CAST(tiab.TELNRDISPLAY AS VARCHAR2(254))) NULLS LAST) row_num
FROM tis.tiab
JOIN tis.tior on tiab.abnr = tior.abnr
WHERE tior.inplnr IN (3797886))
WHERE row_num <= 1
ORDER BY abnr; -
Deleting several rows from a query
I have a query with several rows that have a field with the
string "2 by 4" that I would like to delete. There are other rows
where this same field is "2 by 2" and I don't want to delete those
rows.
What's the syntax? Can I use structdelete? Or is this
data-structure an array?Use the where clause of your sql to select only the records
you want. If you actually need all the records you are getting now,
and you also want a subset of those records, use query of queries
to get your subset. -
Getting a specified number of rows froma query
How can I get the minimum 3 row from a query after a order by in the select
Eg;
SELECT ROWNUM,ROWID, connection_id, GROUP_ID
FROM prov_pending_commands
ORDER BY group_id
4 AAAZWTAAYAAANMiAAA 680932 32702947
3 AAAZWTAAYAAANMgAAB 644610 32703643
2 AAAZWTAAYAAANLrAAB 51925942 32704602
1 AAAZWTAAYAAANLrAAA 61247803 32704613
I need to get only the group ids 32702947,32703643, 32704602 for some other processing.
I checked by getting rownum or row id, but after ordering it gives wrong data
Please need helpHi,
Try this,
select * from (select name, row_number() over (order by name) as row_num from test) row_num
where row_num <= 3
If you are looking for something else explain us more with sample output.
Thanks!
M T
Maybe you are looking for
-
Postfix error after update to 10.6.8
Dear readers and admins After I did update SLS from 10.6.7 to 10.6.8, I got a problem with postfix smtp server. I did google around and found some note, that it is a problem, that a launchd org.postfix.master is running and thath's why the com.apple.
-
HAI, HOW CAN PRINT TEXT VERTICALLY IN SCRIPT ? IS IT , PRINT-CONTROL ZM200 ....TEXT PRINT-CONTROL ZM300 IF IT IS PRINT-COMTROL IS COMMAND ( /: ) OR SOMETHING ELSE THANK YOU ASHOK KUMAR
-
Hi, I am using SHPMNT03 Outbound Idoc for sending the EDI to the customer. How can i know in the IDOC whether its a Shipment Create or Change ? Thank You, Suresh
-
Picture-refreshing frequency issue
Hello, I got this problem: I display 3 different pictures in a sequence. Whole sequence last 1 second (0,3333 per picture) and is repeated continuously. While doing this, I've got some displaying issues - some white flahes occours on the pictures. Th
-
I was able to hook up my macbook pro to my tv using an hdmi cable and all I see is my desk top but not the movie playing on Netflix. Is there some utility I need to do on my computer?