有人可以告诉我,如果这是我正在使用的正确的SQL查询?

时间:2014-07-14 01:07:42

标签: sql postgresql

所以我试图从交易表中找到订单数量。这是我使用过的查询:

   select t.productid,
   EXTRACT(week from t.dt)as Week_,
   count (t.productid) as Orders
   FROM (SELECT distinct productid, dt from Transaction  WHERE client='abc') as t 
   GROUP BY t.productid, Week_
   ORDER BY Week_ asc;

我试图找到按周分组的每个产品的唯一订单。这是正确的方法吗?我真的很感激一些见解和意见。如果我使用这个查询,它只是为每个productid命令为1:

select t.productid,EXTRACT(week from t.dt) as WEEK, count(distinct t.productid) as  Orders  from 
Transaction t
where t.client ='abc'
GROUP BY WEEK, t.productid
ORDER BY WEEK asc;

这是不正确的。

1 个答案:

答案 0 :(得分:1)

不,你的方法并不完全正确。客户可以在一周内以两个不同的订单两次订购相同的产品。据推测,事务表中有某种orderid。如果是这样,你可以这样做:

   SELECT t.productid, EXTRACT(week from t.dt)as Week_, count(distinct orderid) as orders
   FROM Transaction
   WHERE client ='abc'
   GROUP BY t.productid, Week_
   ORDER BY Week_ asc;

如果您想要客户端数量,您可以:

   SELECT t.productid, EXTRACT(week from t.dt)as Week_, count(distinct client) as clients
   FROM Transaction
   GROUP BY t.productid, Week_
   ORDER BY Week_ asc;