views:

140

answers:

2

Hello All,

I am having a table orders

orders (
id  int unsigned not null,
fcr_date  TIMESTAMP,
completion_date TIMESTAMP,
factory_no  varchar(255),
vendor_no  varchar(255))

Please ignore the data type typos if any.

I want to write a sql query that helps me fetch the data per vendor factory. The data to fetch includes the number of orders per vendor factory(a unique group of vendor_no, factory_no), vendor_no, factory_no and the number of orders for which fcr_date is greater than completion_date.

I am new to sql and this particular query seems quite complex to me. I would appreciate if some one could guide me thro on how to write this query.

Thanks.

+3  A: 

You can try something like this

SELECT  vendor_no,
     factory_no,
     COUNT(1),
     SUM(CASE WHEN fcr_date > completion_date THEN 1 ELSE 0 END)
FROM    @orders
GROUP BY vendor_no,
     factory_no
astander
Thank you ... This works in pgsql.. Thanks.
Ishu
Hello,I was wondering if you could help me with this one. The requirement has changed a bit to filter based on %age of orders where fcr date is greater than completion date. I wrote the following query but to no help.SELECT vendor_no As vendor, factory_no As factory, COUNT(1) as count, SUM(CASE WHEN fcr_date > completion_date THEN 1 ELSE 0 END) as filter_orders, ROUND(filter_orders / count * 100, 4) as percent FROM @ordersGROUP BY vendor_no, factory_noHAVING percent>20Postgre complains that it needs a column called percent to do this.
Ishu
+1  A: 
SELECT   vendor_no,
         factory_no,
         COUNT(id),
         SUM(IF(fcr_date > completion_date, 1, 0))
FROM     orders
GROUP BY vendor_no, factory_no;

Works for me with MySQL.

djc
IF seems like a part of PL/PgSQL.. gives me syntax error in pgsql.
Ishu