How do I group by only one column in a SELECT statement?
Hi everyone,
Here is my novice question:
I would like to run a query where I select (display) several columns from my table, yet group (categorize) by one of these columns.
For example:
SELECT A, B, COUNT(A)
FROM TableX
GROUP BY A
I realize now that this is not valid. My first question is why? Doesn't it make sense that you would want to group by only one of the columns? To me, it seems natural that you would most often want to categorize by one attribute, which is why it seems odd that this is not valid. I realize that I can remove column B, but I do want to display that info. I could also change the last statement to GROUP BY A, B to avoid errors, but this will also not display what I am looking for.
In addition to understanding why Oracle is set up this way, I guess I also need to know how I can legally accomplish this query, grouping by A but also displaying the values of B.
Thank you very much for your help!
Holly
Hi everyone,
Thank you for your responses... very interesting and useful. Since I came across inline views in my reading, I tried the approach recommended by g feng, although I am eager to try the other approaches too.
I ended up using an inner join simply to get more descriptive info. on the column that was being counted. With Y representing this second table, Y.B being the column containing the descriptive info., and A being the common key between X and Y, here is the simple code I came up with.
SELECT Y.B, V.*
FROM Y,
SELECT A AV, COUNT (*)
FROM X
GROUP BY A
) V
WHERE V.AV = Y.A
Does this seem correct... anything I need to watch out for?
Thanks again to everyone for your help!!
Holly
Similar Messages
-
How to display number of rows as columns in a select statement? This is on
How to display number of rows as columns in a select statement? This is on 10g R2.
Thanks,
RFor the current (ie. row 1 of 100)
row_number over (order by -pick_a_column_set) as rnfor the total number of columns returned in your query
count(*) over() as total_count -
Hi friends,
I have a create table script as below:
CREATE TABLE GROUPBY_TEST
( NAME VARCHAR2(5),
HIREDATE DATE,
DEPARTMENT VARCHAR2(5),
SALARY NUMBER(5)
Insert script :
INSERT INTO GROUPBY_TEST VALUES ('A','1-JAN-2000','XYZ',1000);
INSERT INTO GROUPBY_TEST VALUES ('A','1-FEB-2000','ABC',5000);
INSERT INTO GROUPBY_TEST VALUES ('A','1-APR-2000','DDD',5000);
INSERT INTO GROUPBY_TEST VALUES ('B','10-JAN-2000','EEE',1000);
INSERT INTO GROUPBY_TEST VALUES ('B','10-FEB-1999','FFF',500);
INSERT INTO GROUPBY_TEST VALUES ('C','15-MAY-2005','GGG',500);
INSERT INTO GROUPBY_TEST VALUES ('C','27-JUN-2003','LLL',10000);
My table data looks like :
SELECT * FROM GROUPBY_TEST;
NAME HIREDATE DEPAR SALARY
A 01-JAN-00 XYZ 1000
A 01-FEB-00 ABC 5000
A 01-APR-00 DDD 5000
B 10-JAN-00 EEE 1000
B 10-FEB-99 FFF 500
C 15-MAY-05 GGG 500
C 27-JUN-03 LLL 10000
7 rows selected.
I want output as:
Name HAREDATE DEPT SAL
A 01-APR-00 DDD 5000
B 10-JAN-00 EEE 1000
C 15-MAY-05 FFF 500
i want to have max(HIREDATE) records group by NAME only and NOT BY DEPARTMENT AND SAL.
When i tried query as below:
select name,max(hiredate),department,salary from groupby_test
group by name,department,salary;
It returned all 7 records which i dont want
can some one help me getting neccessary output ?
Thanks a lot
JPA way :
SQL> select name, hiredate, department, salary
2 from (select a.*, dense_rank() over (partition by name order by hiredate desc) dr from groupby_test a)
3 where dr = 1;
NAME HIREDATE DEPAR SALARY
A 01/04/00 DDD 5000
B 10/01/00 EEE 1000
C 15/05/05 GGG 500
SQL> An other way without subquery :
SQL> select name,
2 max(hiredate) keep (dense_rank last order by hiredate) hiredate,
3 max(department) keep (dense_rank last order by hiredate) department,
4 max(salary) keep (dense_rank last order by hiredate) salary
5 from groupby_test
6 group by name;
NAME HIREDATE DEPAR SALARY
A 01/04/00 DDD 5000
B 10/01/00 EEE 1000
C 15/05/05 GGG 500
SQL> Nicolas.
Ok, too slow, and too late for me now...
Message was edited by:
N. Gasparotto -
How to make only one column non reorderble
I want to make only one column (Column 0) of my JTable non reorderble.
I also want to make the same column non resizable and I want to give it a specific size.
Please help me on this?I have implemented a RowHeaderTable class which displays 1, 2, 3, ... in the first column. The column is in the scrollpane's RowHeaderView, so it is not resizable nor reorderable. But its width can be set in your code. Maybe this is what you need.
Use the class the same way you use a JTable, except 3 added methods:
getScrollPane();
setMinRows(int r);
setRowHeaderWidth(int w);
Note: The table works perfectly in skinless L&F, such as the default java L&F. It looks ugly in Liquid L&F because I don't know how to steal column header's UI to use on a JList. If someone can help me on this one, I thank you in advance.
* RowHeaderTable.java
* Created on 2005-3-21
* Copyright (c) 2005 Jing Ding, All Rights Reserved.
* Permission to use, copy, modify, and distribute this software
* and its documentation for NON-COMMERCIAL purposes and without
* fee is hereby granted provided that this copyright notice
* appears in all copies.
* JING DING MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE
* SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. JING DING
* SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT
* OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
import java.awt.BorderLayout;
import java.awt.Component;
import javax.swing.AbstractListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
* @author Jing Ding
public class RowHeaderTable extends JTable {
private int minRows = 10; // Minimum size of the row header.
private static final int DEFAULT_WIDTH = 30;
private JScrollPane jsp;
// The row header is a JList with the same appearance as the column header.
private JList rowHeader;
// Repaint row header whenever the table inserts or deletes rows.
private TableModelListener tmListener = new TableModelListener(){
public void tableChanged(TableModelEvent e){
if(e.getType() != TableModelEvent.UPDATE)
rowHeader.repaint();
/** Create a new instance of RowHeaderTable.
* @param model
public RowHeaderTable(TableModel model){
setModel(model);
initializeHeader();
jsp = new JScrollPane(this);
jsp.setRowHeaderView(rowHeader);
private void initializeHeader(){
rowHeader = new JList(new AbstractListModel(){
public int getSize(){ return Math.max(getModel().getRowCount(), minRows); }
public Object getElementAt(int index){ return "" + ++index; }
setRowHeaderWidth(DEFAULT_WIDTH);
rowHeader.setFixedCellHeight(getRowHeight());
rowHeader.setCellRenderer(new TableRowHeaderRenderer());
public void setRowHeaderWidth(int w){
rowHeader.setFixedCellWidth(w);
public void setMinRows(int m){ minRows = m; }
public void setModel(TableModel model){
super.setModel(model);
model.addTableModelListener(tmListener);
/**Use this method to get the scrollPane, instead of new JScrollPane(table).
* @return
public JScrollPane getScrollPane(){ return jsp; }
protected class TableRowHeaderRenderer implements ListCellRenderer{
TableCellRenderer colHeaderRenderer;
public TableRowHeaderRenderer(){
JTableHeader header = getTableHeader();
TableColumn aColumn = header.getColumnModel().getColumn(0);
colHeaderRenderer = aColumn.getHeaderRenderer();
if(colHeaderRenderer == null)
colHeaderRenderer = header.getDefaultRenderer();
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean hasFocus){
return colHeaderRenderer.getTableCellRendererComponent(
RowHeaderTable.this, value, isSelected, hasFocus, -1, -1);
public static void main(String[] args){
try {
UIManager.setLookAndFeel("com.birosoft.liquid.LiquidLookAndFeel");
}catch (Exception e){ e.printStackTrace(); }
String[] columnNames = {"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};
Object[][] data = {
{"Mary", "Campione", "Snowboarding", new Integer(5), new Boolean(false)},
{"Alison", "Huml", "Rowing", new Integer(3), new Boolean(true)},
{"Kathy", "Walrath", "Knitting", new Integer(2), new Boolean(false)},
{"Sharon", "Zakhour", "Speed reading", new Integer(20), new Boolean(true)},
{"Philip", "Milne", "Pool", new Integer(10), new Boolean(false)}
DefaultTableModel dtm = new DefaultTableModel(data, columnNames);
RowHeaderTable rht = new RowHeaderTable(dtm);
rht.setMinRows(0);
JFrame frame = new JFrame("RowHeaderTable Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(rht.getScrollPane(), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
dtm.addRow(new Object[]{"Mary", "Campione", "Snowboarding", new Integer(5), new Boolean(false)});
dtm.addRow(new Object[]{"Mary", "Campione", "Snowboarding", new Integer(5), new Boolean(false)});
dtm.addRow(new Object[]{"Mary", "Campione", "Snowboarding", new Integer(5), new Boolean(false)});
} -
there is a scenario in informatica..where we can select more than one rows and group by on only one row..its possible in informatica..
so can any one tell how to sql for those type of scenarios
For example there are
SEQUENCE_ID NUMBER NOT NULL,
SAT_ID VARCHAR2(30 BYTE) NOT NULL,
MFG_ID VARCHAR2(99 BYTE),
SOLD_DT DATE,
VIN VARCHAR2(30 BYTE)
HE IS SELECTING ALL THE COLUMNS AND GROUPING BY ON SAT_ID ..so do any one tell how to write sql in that scenarioin oracle you can have groupings without having to group all of the columns in the select clause by using an analytic query.
select a.*
from (select sequence_id,
mfg_id,
sold_dt,
vin,
row_number() over (partition by mfg_id order by sold_dt) rn
from <table>
where <conditions>) a
where a.rn = 1
try to post some sample data and output. we might be able to come up with some simple query that might be compatible or supported by informatica queries. -
Set filter for only one column in tableview
Hi
i am using in MVC a htmlb:tableview with filter in only one column of 8.
This is all working fine, except that the user can enter a searchsting in the filterfield for all columns, but in handle_event (of the controller) ; i only react to a text in the filterfield of column 4 and ignore all other filtertext , which were maybe entered in the other columns.
My question:
how can i enter the filter only for one column, in a way that the user cannot enter any text in the filterfield of the other columns, only in column 4 ?
my view:
<htmlb:tableView id = "requirements"
table = "//model/pdst_reqs"
filter = "APPLICATION"
keyColumn = "EXTID"
iterator = "<%=model%>"
footerVisible = "FALSE"
encode = "TRUE"
visibleRowCount = "<%=model->rowcount%>"
width = "100%"/>
Best Regards
BrittaYou can disbale the Filter for the particular column by setting the DISABLE_FILTER in the Iterator method IF_HTMLB_TABLEVIEW_ITERATOR~GET_COLUMN_DEFINITIONS. Here is the sample code
method IF_HTMLB_TABLEVIEW_ITERATOR~GET_COLUMN_DEFINITIONS .
CLEAR p_column_definitions.
CLEAR p_overwrites.
data tv_column TYPE TABLEVIEWCONTROL.
tv_column-COLUMNNAME = 'FLDATE'.
tv_column-SORT = 'X'.
tv_column-EDIT = 'X'.
tv_column-ONCELLCLICK = 'MyCellClick1'.
tv_column-title = 'Date '.
APPEND tv_column TO p_column_definitions.
CLEAR tv_column.
tv_column-COLUMNNAME = 'PRICE'.
tv_column-horizontalAlignment = 'right'.
tv_column-verticalAlignment = 'middle'.
tv_column-ONCELLCLICK = 'MyCellClick2'.
tv_column-title = 'Currency'.
tv_column-EDIT = 'X'.
tv_column-DISABLE_FILTER = 'X'. " <-------Like this
APPEND tv_column TO p_column_definitions.
endmethod.
Hope this will solve your problem.
Raja -
How to flag only ONE image when several selected in 'N' mode ?
Hi,
I want to compare several images in a same serie. I select. I press N key, then I select in strip bottom bar the group of picture.
I want to put a flag (or star) to only the ONE I prefer, but all pics get the flags or star...
I need to take out the reject by clicking each X of each pic to threw them away, and finally pick only the on I want...
How to pick or star only ONE image on N mode (ENSEMBLE Mode in french LR)
Manys tks
FredI can't reproduce your issue on Mac or Windows. Quite often when odd ball behaviour arises it's an indication that Lr preference file has become corrupt. Have you tried trashing your Lr preference file then relaunching the application? The name and location for the preference file described here Preference and other file locations in Lightroom 5
-
Copy only one column of the workbook1 and paste it in another workbook 2
Hello Rishi. Please help me with this how to copy only one column C of the workbook1 and paste it in another workbook 2 in Column D so that When user execute workbook1 . and then execute workbook2 . Column D is automatically populated in Workbook2 based on the data in Column C in workbook 1
Please help
Thanks
SoniyaHi Soniya
As I mentioned earlier, I haven't come across a situation of copying data from one workbook to another. However, for doing some dynamic modifications within the different sheets of the same workbook, you can refer to the following thread:
Comparing two queries with VBA macro
Thanks,
Rishi -
Only one column was record on Trigger
Dear Experts,
I've created SQL Trigger, it has five column, but only one column was recorded when Trigger's fired, another filled by NULL value
please your valuable suggestion & helps
thank you
warmest regardsTriggers are fired by INSERT not matter how many rows it will generate and it is perfectly possible to have NULLs if columns allow it..
If you want to prevent from entering NULLs, please examine inserted virtual table to filter out the data which contains NULLs.
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence -
How can I Move data from one column to another in my access table?
I have two columns, one that stores current month’s data and one that stores last month’s data. Every month data from column 2 (this month’s data) needs to be moved to column 1 that holds last month’s data. I then null out column 2 so I can accumulates this month’s data.
I understand how to drop a column or add a column, how do I transfer data from one column to another.
Here is my trial code:
<cfquery name="qQueryChangeColumnName" datasource="#dsn#">
ALTER TABLE leaderboard
UPDATE leaderboard SET points2 = points3
</cfquery>
Unfortunately, I get the following error:
Error Executing Database Query.
[Macromedia][SequeLink JDBC Driver][ODBC Socket][Microsoft][ODBC Microsoft Access Driver] Syntax error in ALTER TABLE statement.
How can I transfer my data with the alter table method?I looked up the Access SQL reference (which is probably a
good place to start when having issues with Access SQL), and
it suggests you probably need a WHERE clause in there.
I agree the documentation is a good place to start. But you should not need a WHERE clause here.
Too few parameters. Expected 1.
If you run the SQL directly in Access, what are the results? At the very least, it should provide a more informative error message.. -
Imported CD songs are each put into a separate album. How can I group them in one album?
Look at Steve MacGuire's helpful article: http://samsoft.org.uk/iTunes/grouping.asp
-
Access for update only one column in table?
Hi all,
My need is to grant access for update only one column c1 in table t1.
I guess I should use view, could you please give me some example? Maybe other ideas?Hi,
You can grant privileges on individual columns.
GRANT UPDATE (c1)
ON t1
TO grantee_name;Look up GRANT in the SQL language manual. Annoyingly, in recent editions of the manual, GRANT is not indexed, but it's in alphabetic order with all the other statements:
http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_9013.htm#i2155015 -
How do I pull up only one specific calendar at a time on my iPhone (i.e. 'home calendar')?
Thanks!In the calendar app, press the button in the upper left, "Calendars" and turn off/on the ones you want/don't want.
-
How to change font in just one column of JTable
I have a table with 4 column.
I want to have Courier font in column number 2, and Arial in columns number 1, 3 and 4.
With:
table.setFont(new Font("Courier New", Font.PLAIN, 12));
I can set fonts in all columns but how to set font in just one column.
Thanks
SrdanHi,
there are 2 methods of JTable where every rendering resp. editing component "comes" through - prepareRenderer(...) and prepareEditor(....) - by overwriting this methods and calling its super method first you get the component and can manipulate it before you return it. This component is exactly that, what is used for rendering resp. editing afterwards.
greetings Marsian -
EA2: Code is generated for only one column with Domain check constraint.
I created a Domain with a Value List (Y or N - Yes or No) and used that domain for two columns in the same table. But for only one column (the last one) the check appears in the generated DDL.
After I enabled the "Use Domain Constraints" both checks appear in the DDL, but one as an inline check constraint and one as an "Alter table add contraint.."
Once I changed the naming Template for the check constraint, both constraints are generated as an Alter table clause. The inline check constraint is only generated when the name of the constraint (according to the template) is too long. It would be nice if I could choose if I want an inline or a separate check constraint definition.
Edited by: Roel on Nov 23, 2010 11:55 AM
Edited by: Roel on Nov 23, 2010 12:02 PMI logged ER for that
Philip
Maybe you are looking for
-
Is there an ETA for the availability of Volume Purchase Program in UK?
The Volume Purchase Program in the US looks to be an incredibily useful service. http://www.apple.com/business/vpp/ Does anyone have any information about when/if this same service will be availabile to UK businesses? Many thanks
-
Deletion and Creation of storage location.
Dear Experts, Plz advise how can we un-assign any storage location from any material & how can we create the new storage location. Regards Sumit Kalyan
-
New Message, reply, or forward window does not open in Outlook for Mac 2011
New Message, reply, or forward window does not open in Outlook for Mac 2011 Outlook acts as if I am pressing a dummy button.
-
Is ODI 12c included in 12c Oracle Server License?
Hello, I'm looking into the licensing information and the only thing I was able to find out about ODI 12c is for Data integrator Enterprise Edition, that costs some 23k per CPU. Plus Golden Gate for access to non-Oracle data sources. Can someone plea
-
Hello, My name is Ashvin Ghisyawan and I'm from Holland. I'm a professional wedding photographer. Since a few months a use Indesign to make the spread of my wedding albums. Does anyone know a company of templates that I can use to quickly make my spr