学习SQL管理员的QUERY帮助

时间:2013-06-29 01:00:46

标签: sql

我有这个问题:

SELECT count(*) from
(
SELECT custid, count(*) as OrderCount
FROM orderinfo
WHERE preparedate between '2011-06-01' and '2011-12-31'
GROUP by CUSTID
) COUNTDB
WHERE Ordercount > '20'

返回:901 CustID的

如果我跑:

SELECT * from
(
SELECT custid, count(*) as OrderCount
FROM orderinfo
WHERE preparedate between '2011-06-01' and '2011-12-31'
GROUP by CUSTID
) COUNTDB
WHERE Ordercount > '20'

它返回单个CustID及其订单计数的列表。

custid OrderCount
1001   24
1010   30
1033   36

...

我希望做的是查看查询中返回的客户ID中有多少,已在较晚的日期范围内下订单,例如“2012-06-01”和“2012-12-31”

我的目标是:

让我看看我是否可以用另一种方式来描述。

我需要查看2011年已提交超过20个订单的CustID总数(提供日期范围)。然后,第二步是看看有多少SAME客户在同一天的2012日期范围内下了订单

3 个答案:

答案 0 :(得分:3)

我假设你的架构看起来像这样:

OrderInfo ( CustId, PrepareDate )

(嗯,简单,嗯?)

因此,如果我理解正确,您需要在两个日期之间下订单的客户列表,并且他们已经下了20多个订单。这很简单:

SELECT
    CustId,
    Count(*) AS OrderCount
FROM
    OrderInfo
WHERE
    PrepareDate BETWEEN '2012-06-01' and '2012-12-31'
GROUP BY
    CustId
HAVING
    OrderCount > 20

答案 1 :(得分:0)

也许像这样的作品:

SELECT
   custid
FROM
   orderinfo
WHERE
     preparedate between '2011-06-01' and '2011-12-31'
 AND custid IN (
       SELECT
          custid
       FROM
          orderinfo
       WHERE
            preparedate between '2011-06-01' and '2011-12-31'
       GROUP BY
          custid
       HAVING
          COUNT(*) > 20
 )

答案 2 :(得分:0)

  

让我看看我是否可以用另一种方式来描述。我需要看到总数   2011年已发出超过20个订单的CustID的数量   (提供日期范围)。然后,第二步将是看多少   那些SAME客户已经在2012年的日期范围内下了订单   同一天@AlexandreP.Levasseur

请试试这个。此外,如果您在尝试帮助时为我们制作一个SQLFiddle来测试我们的查询,那将会很方便!

SELECT
    CustId
FROM
    OrderInfo
WHERE
    PrepareDate BETWEEN '2012-06-01' and '2012-12-31' AND
    CustId IN 
        (SELECT
            DISTINCT CustId
        FROM
            OrderInfo
        WHERE
            PrepareDate BETWEEN '2011-06-01' and '2011-12-31'
        GROUP BY
            CustId
        HAVING
            Count(*) > 20)