SQL列具有不同条件的子查询

时间:2014-12-18 11:06:03

标签: sql join subquery

让我们说有两个表,[产品]和[Quantiy]。

我需要在两者中选择一个连接,以便构建一个包含每个产品总数量的表格。 我知道在香草加入中这是做谁的。我的问题是我需要3列一个[PreviewTotal]我应该有这个总数量,直到昨天,无论数量其他[TodaytotalPos]的数量今天和正数和其他[TodaytotalNeg]今天只有负数。

结果如:

[Products] [PreviewTotal]  [TodaytotalPos] [TodaytotalNeg]

AAPL           20,000         500             -700

MCD           15,000           NULL            -300

BAC           -30,000          2,000           NULL

结构样本: Producst:

[id]  [name]
1     AAPL
2     MCD
3     BAC

数量:

[date]   [Id_Product]   [Quantity]
12/16         1            500
12/16         2            -300
12/17         1            1,000
12/18         3            5,500
12/18         1            -2,000

2 个答案:

答案 0 :(得分:0)

根据您指定的规则,我认为您只是在寻找条件聚合。您的查询看起来像这样:

select p.name,
       sum(case when [date] < cast(getdate() as date) then quantity end) as PreviewTotal,
       sum(case when [date] = cast(getdate() as date) and quantity > 0
                then quantity end) as TodayTotalPos,
       sum(case when [date] = cast(getdate() as date) and
                quantity < 0 then quantity end) as TodayTotNeg
from products p join
     quantity q
     on q.id_product = p.id
group by p.name
order by p.name;

但是,根据这些规则,您所需的结果与输入数据不匹配。

答案 1 :(得分:0)

在SQL Server中,如果条件为true或false,则可以使用CASE选择字段值。我假设您的[Products]表至少包含ProductId和ProductName,您的[Quantity]表至少包含ProductId,Qty和SoldDate。

-- get the time of midnight, the start of today:
DECLARE Today datetime;
SELECT DATEADD(DAY, DATEDIFF(DAY, '19000101', GETDATE()), '19000101') INTO Today

-- get the totals
SELECT Products.ProductName, 
    SUM(
      CASE 
        WHEN Quantity.SoldDate >= Today THEN Quantity.Qty
        ELSE 0
      END) AS PreviewTotal,
    SUM(
      CASE 
        WHEN Quantity.Qty> 0 AND Quantity.SoldDate >= Today) THEN Quantity.Qty
        ELSE 0
      END) AS TodaytotalPos,
    SUM(
      CASE 
        WHEN Quantity.Qty< 0 AND Quantity.SoldDate >= Today THEN Quantity.Qty
        ELSE 0
      END) AS TodaytotalNeg
FROM Products JOIN Quantity on Products.ProductId = Quantity.ProductId
GROUP BY ProductName