比较月份字段SQL Server

时间:2018-03-07 15:09:27

标签: sql sql-server tsql

当前演示:http://sqlfiddle.com/#!18/7acdc/17

我正在寻找在特定月份中添加了多少项目,但之后总共有多少项目从未订购过。

表:

CREATE TABLE Item (
    ItemNo varchar(10)
   ,DateAdded varchar(10)
);

CREATE TABLE Order1 (
    OrderNo int,
    ItemNo varchar(10),
    OrderDate varchar(10)
);


INSERT INTO Item (ItemNo, DateAdded)
VALUES ('111', 'Jan-17'),
('222', 'Jan-17'),
('333', 'Jan-17'),
('444', 'Feb-17'),
('555', 'Feb-17'),
('666', 'Feb-17');

INSERT INTO Order1 (ItemNo, OrderDate)
VALUES ('111', 'Jan-17'),
('111', 'Feb-17'),
('222', 'May-17'),
('333', 'Jan-17'),
('333', 'March-17'),
('444', 'Jan-17');

目前我有:

SELECT  
-- b.OrderDate,
    A.DateAdded,
    COUNT(DISTINCT A.ItemNo) AS [Items Added],
    COUNT(CASE WHEN c.ItemNo IS NULL THEN 1 END) as [Items Never Ordered]
FROM    Item a
    CROSS JOIN (SELECT  DISTINCT OrderDate FROM Order1) b
    LEFT JOIN Order1 c
        ON a.ItemNo = c.ItemNo
            AND b.OrderDate = c.OrderDate 

  GROUP BY A.DateAdded

产生:

| DateAdded | Items Added | Items Never Ordered |
|-----------|-------------|---------------------|
|    Feb-17 |           3 |                  11 |
|    Jan-17 |           3 |                   7 |

但我正在寻找一个结果集,如:

| DateAdded | Items Added | Items Never Ordered |
|-----------|-------------|---------------------|
|    Feb-17 |           3 |                   2 |
|    Jan-17 |           3 |                   0 |

我正在努力让这个工作。我是否需要子查询或其他内容来单独匹配项目。任何人都可以把我推向正确的方向吗?感谢

1 个答案:

答案 0 :(得分:1)

也许这个:

WITH DataSource AS
(
    SELECT A.*
         ,MAX([IsEverOrdered]) OVER (PARTITION BY ItemNo) [IsEverOrdered]
    FROM Item A
    OUTER APPLY
    (
        SELECT 1 [IsEverOrdered]
        FROM Order1 B
        WHERE A.[ItemNo] = B.[ItemNo]
    ) DS
)
SELECT DateAdded
      ,COUNT(DISTINCT ItemNo) AS [Items Added]
      ,SUM(CASE WHEN [IsEverOrdered] IS NULL THEN 1 ELSE 0 END) AS [Items Never Ordered]
FROM DataSource
GROUP BY DateAdded;

enter image description here

如果订购了任何商品,Commant Table Expression将返回。然后,我们只需要计算/总和:

enter image description here