SQL SUM然后算?

时间:2018-07-29 02:44:27

标签: mysql sql count sum

表Historical_Inventory

列:日期,产品ID,WHStock,已分配库存

我想计算在日期x和y之间产品(WHstock-库存分配)<= 0的次数,其中Prod_ID =“ id1”

有什么想法吗?

我一直沿着

SELECT Count `Prod_ID`
     , sum((`WHStock`-`Stock_Allocated`)) as Stock 
  from Historic_Inventory 
 WHERE `Date` Between '2018-04-01'and '2018-08-01'
   AND Stock <= 0

但是效果不是很好。

2 个答案:

答案 0 :(得分:0)

尝试一下:

#include <stdio.h>
#include <stdlib.h>

int main() {
    /*Here i and j are for loop counters,temp for swapping
    count  for total number of elements,array for elements*/
    int i, j, temp, count;
    printf("How many numbers are you going to enter?\n");
    scanf("%d",&count);
    int n[count];
    printf("Enter %d elements\n",count);
    //storing elements in the array
    for(i = 0; i < count; i++) {
        scanf("%d", &n[i]);
    }
    //Implementation of insertion sort algorithm
    for(i = 1; i <= count; i++) {
        temp = n[i];
        j = i-1;
        while(temp < n[j]) {
            n[j+1] = n[j];
            j--;
        }
        n[j+1] = temp;
     }
     printf("Order of sorted elements\n");
     for(i = 0; i < count; i++) {
        printf("%d\n",n[i]);
     }
    return 0;
}

答案 1 :(得分:0)

我想你想要

SELECT COUNT(*)
FROM (SELECT Prod_ID, SUM(WHStock - Stock_Allocated) as Stock 
      FROM Historic_Inventory 
      WHERE `Date` Between '2018-04-01' and '2018-08-01'
      GROUP BY Prod_ID
     ) x
WHERE Stock <= 0;

嗯。 。 。这将计算产品的数量,该值为负。

也许你想要

select hi.*
       (@stock := @stock + (WHStock - Stock_Allocated)) as stock
from (select hi.*
      from historic_inventory hi
      where prod_id = ?
      order by date
     ) hi cross join
     (select @stock := 0) params
having stock < 0;