Solved

TSQL help

Posted on 2015-02-17
6
73 Views
Last Modified: 2015-02-27
How can I write a sql statement from tOrders table where I only want to return the result for min products seq.    for example

tProductSeq
---------------------
ProductTYpe      seq
Dairy                        1
Fruits                        2
Vagitables      3
Paper                        4


tOrders
-------------------------------------------------------
OrderID      producttype      qty
2      Fruits      22
3      Vagitables      5
4      Paper      2
1      Fruits      36
3      Paper      24
1      Dairy      23
2                Paper       25
8                Paper       24

Tsql result should be as below
OrderID      producttype      qty
2      Fruits                     22
3      Vagitables      5
4      Paper                       2
1      Dairy                     23
8                Paper       24


select * from tOrders O
where O.tProductType in (select top 1 PT.producttype PT from tProductSeq  PT where O.tProductType = PT.producttype  order by seq)
0
Comment
Question by:Bharat Guru
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
LVL 34

Expert Comment

by:Mike Eghtebas
ID: 40615398
SELECT pc.producttype ,    COUNT(o.OrderID) As seq 
FROM tOrders o Inner Join productCategory pc
On pc.producttype= o.producttype
GROUP BY pc.producttype
ORDER BY COUNT(o.OrderID)

Open in new window


This post has been revised
0
 
LVL 48

Accepted Solution

by:
PortletPaul earned 500 total points
ID: 40615442
Please try the following:
SELECT
      O.OrderID
    , O.producttype
    , O.qty
FROM productCategory PC
INNER JOIN (
      SELECT
            OrderID
          , producttype
          , qty
          , ROW_NUMBER() OVER (PARTITION BY producttype
                               ORDER BY OrderId DESC) AS RN
) AS O ON PC.producttype = O.producttype
            AND O.RN = 1
;

Open in new window

It appears that you want "the latest" order rows but the only information I can see to achieve "latest" is the orderid.

Note, the sequence of tables could be reversed and/or there may be a need to an outer join, but this isn't indicated by the sample data.
0
 

Author Comment

by:Bharat Guru
ID: 40615740
Above solution seems little tricky, how about if I import the data into the  ttemporder table and some how if i can delete the  records except min seq to get the final result?

I was to get the result inside the stored procedure so if it's necessary its it's ok get the result in two steps.
0
Why You Need a DevOps Toolchain

IT needs to deliver services with more agility and velocity. IT must roll out application features and innovations faster to keep up with customer demands, which is where a DevOps toolchain steps in. View the infographic to see why you need a DevOps toolchain.

 
LVL 48

Expert Comment

by:PortletPaul
ID: 40615778
This result:
| ORDERID | PRODUCTTYPE | QTY |
|---------|-------------|-----|
|       1 |       Dairy |  23 |
|       2 |      Fruits |  22 |
|       8 |       Paper |  24 |
|       3 |  Vagitables |   5 |

Open in new window


Produced by this query:
SELECT
      O.OrderID
    , O.producttype
    , O.qty
FROM tProductSeq PC
INNER JOIN (
      SELECT
            OrderID
          , producttype
          , qty
          , ROW_NUMBER() OVER (PARTITION BY producttype
                               ORDER BY OrderId DESC) AS RN
      FROM tOrders
) AS O ON PC.producttype = O.producttype
            AND O.RN = 1
;

Open in new window


From the sample data of the question.

ROW_NUMBER() is an efficient system function, and is frequently used to locate conditions such as "the latest" or "most recent" rows.

If the tables are exactly as you indicate in the question then you can get the same result from:
SELECT
      O.OrderID
    , O.producttype
    , O.qty
FROM (
      SELECT
            OrderID
          , producttype
          , qty
          , ROW_NUMBER() OVER (PARTITION BY producttype
            ORDER BY OrderId DESC) AS RN
      FROM tOrders
    ) AS O
WHERE RN = 1

Open in new window


I would regard using temp tables and a multi-staged approach as more tricky than using ROW_NUMBER()

see it working at: http://sqlfiddle.com/#!3/f97f9/6

{+ edit}
The expected result in your question isn't met by these queries. Appears I don't understand the logic of arriving at the expected result, can you explain what that logic is?
0
 
LVL 48

Expert Comment

by:PortletPaul
ID: 40615803
In the question your sql contains: order by seq

So, if the expected is ordered that way it would look like this:
OrderID producttype   qty
1       Dairy         23
2       Fruits        22
3       Vagitables     5
4       Paper          2
8       Paper         24

Open in new window


Why are there two rows in this output for Paper?

If I include order by seq in my query that joins the 2 tables - and output that column the result is:
| ORDERID | PRODUCTTYPE | QTY | SEQ |
|---------|-------------|-----|-----|
|       1 |       Dairy |  23 |   1 |
|       2 |      Fruits |  22 |   2 |
|       3 |  Vagitables |   5 |   3 |
|       8 |       Paper |  24 |   4 |

Open in new window


SELECT
      O.OrderID
    , O.producttype
    , O.qty
    , PC.seq
FROM tProductSeq PC
INNER JOIN (
      SELECT
            OrderID
          , producttype
          , qty
          , ROW_NUMBER() OVER (PARTITION BY producttype
                               ORDER BY OrderId DESC) AS RN
      FROM tOrders
) AS O ON PC.producttype = O.producttype
            AND O.RN = 1
ORDER BY PC.seq

Open in new window

0
 

Author Closing Comment

by:Bharat Guru
ID: 40635723
Thanks
0

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
how to solve "recursive" database tables 2 59
Report 8 27
DMV Script to find how many times statistics are utilized 2 30
t-sql left join 2 34
In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question