4

Please help me with the following

Question:

+------+----------+
| Name | Sub-name |
+------+----------+
| A    | x        |
| A    | x        |
| B    | x        |
| A    | y        |
| B    | y        |
+------+----------+

Desired Result:

+------+----------+-------+
| Name | Sub-name | Count |
+------+----------+-------+
| A    | x        |     2 |
| A    | x        |     2 |
| B    | x        |     1 |
| A    | y        |     1 |
| B    | y        |     1 |
+------+----------+-------+

Three columns Name, Subname, Count

I want to partition based on both name and subname.

7
  • 1
    Please read How to Ask. What have you tried?
    – user812786
    Commented Sep 17, 2015 at 17:47
  • Im sorry if the question I asked is not proper. I tried count(Name) OVER (PARTITION BY Sub-NAME) AS Count Commented Sep 17, 2015 at 17:56
  • Okay, so what does that output that is incorrect? (FYI that is the sort of thing you should have in your question - people on here will help you debug code that you've already written, but they're less likely to just write it for you.)
    – user812786
    Commented Sep 17, 2015 at 18:12
  • not exactly sure what you are after but it sounds you want to check out rollup or cube. Commented Sep 17, 2015 at 18:13
  • Seems like you're on the right track with count() over (), but the partition specification looks a bit off.
    – mustaccio
    Commented Sep 17, 2015 at 18:22

3 Answers 3

9

SQL Fiddle

Oracle 11g R2 Schema Setup:

CREATE TABLE test ( Name, "Sub-name" ) AS
          SELECT 'A', 'x' FROM DUAL
UNION ALL SELECT 'A', 'x' FROM DUAL
UNION ALL SELECT 'B', 'x' FROM DUAL
UNION ALL SELECT 'A', 'y' FROM DUAL
UNION ALL SELECT 'B', 'y' FROM DUAL;

Query 1:

SELECT Name,
       "Sub-name",
       COUNT( 1 ) OVER ( PARTITION BY "Sub-name", Name ) AS "Count"
FROM   test

Results:

| NAME | Sub-name | Count |
|------|----------|-------|
|    A |        x |     2 |
|    A |        x |     2 |
|    B |        x |     1 |
|    A |        y |     1 |
|    B |        y |     1 |
0
1

Try this:

select name, sub_name, count(name) over (partition by name, sub_name) as count from table

0
0

select ra.Name,ra.sub-name,ta.count from table ra inner join (select Name,sub-name,count(*) from table group by Name,sub-name)ta on ra.Name=ta.Name on ra.sub-name=ta.sub-name order by sub-name desc

Really i don't understand why we need to use partition for this solution.Even the above join query works fine...hope it should....

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.