如何根据包括行顺序在内的特定条件进行SQL查询计数

时间:2016-05-26 14:58:04

标签: sql sql-server count

我遇到了SQL查询所需的某些逻辑。鉴于我有一张表:

+----------+-------+------------+
| product  | valid | Date       |
+----------+-------+------------+
| 1        | null  | 2016-05-10 |
| 1        | null  | 2016-05-09 |
| 1        | yes   | 2016-05-08 |
+----------+-------+------------+

此表由简单查询生成:

SELECT * FROM products WHERE product = 1 ORDER BY date desc

现在我需要做的是创建一个查询,按日期顺序计算某些产品的空数,直到有一个yes值。所以上面的例子计数将是2,因为有2个空值,直到是。

+----------+-------+------------+
| product  | valid | Date       |
+----------+-------+------------+
| 2        | null  | 2016-05-10 |
| 2        | yes   | 2016-05-09 |
| 2        | null  | 2016-05-08 |
+----------+-------+------------+

上面会返回1,因为有1为空,直到是。

+----------+-------+------------+
| product  | valid | Date       |
+----------+-------+------------+
| 3        | yes   | 2016-05-10 |
| 3        | yes   | 2016-05-09 |
| 3        | null  | 2016-05-08 |
+----------+-------+------------+

上面会返回0。

3 个答案:

答案 0 :(得分:1)

你需要一个像这样的相关子查询:

SELECT COUNT(*) 
FROM products AS p1
WHERE product = 1 
  AND Date >
    ( -- maximum date with 'yes'
      SELECT MAX(Date) 
      FROM products AS p2
      WHERE p1.product = p2.product 
        AND Valid = 'yes'
    )

答案 1 :(得分:0)

这应该这样做:

select count(1) from table where valid is null and date > (select min(date) from table where valid = 'yes')

答案 2 :(得分:0)

不确定您提供的逻辑是否涵盖了所有可能的奇怪和奇妙的极端场景,但下面的代码将完成您的工作:

select a.product,
count(IIF(a.valid is null and a.date >maxdate,a.date,null)) as total  
from sometable a 
inner join (
select product, max(date) as Maxdate
from sometable where valid='yes' group by product
            ) b 
on a.product=b.product group by a.product