结果为空时的SQL查询

时间:2016-01-21 06:57:47

标签: sql sql-server tsql

我有一张这样的表

USER     itemnumber     datebought (YYYYmmDD)

a           1            20160101
b           2            20160202
c           3            20160903
d           4            20160101

现在我必须显示每个用户在20160202(2016年2月2日)之后购买的商品总数

我用过

SELECT USER, COUNT(itemnumber)<br/>
FROM TABLE<br/>
WHERE datebought >= 20160202<br/>
GROUP BY USER<br>

它给了我结果

b        1
c        1

但我想这样

a      0
b      1
c      1
d      0

请告诉我这方面最快速的方法/有效方法是什么?

4 个答案:

答案 0 :(得分:3)

试试这个,

       DECLARE @table TABLE
  (
     [USER]     VARCHAR(1),
     itemnumber INT,
     datebought DATE
  ) 
INSERT INTO @TABLE VALUES
('a',1,'20160101'),
('b',2,'20160202'),
('b',2,'20160202'),
('b',2,'20160202'),
('c',3,'20160903'),
('d',4,'20160101')

SELECT *
FROM   @TABLE

SELECT [USER],
       Sum(CASE
             WHEN datebought >= '20160202' THEN 1
             ELSE 0
           END) AS ITEMCOUNT
FROM   @TABLE
GROUP  BY [USER] 

答案 1 :(得分:1)

使用此

SELECT USER, COUNT(itemnumber)
       FROM TABLE
       WHERE datebought >= 20160202
       GROUP BY USER

答案 2 :(得分:0)

虽然这个查询对于大量数据不是一个好主意:

SELECT USER, COUNT(itemnumber)
  FROM TABLE
 WHERE datebought >= 20160202
 GROUP BY USER
 UNION
SELECT DISTINCT USER, 0
  FROM TABLE
 WHERE datebought < 20160202

答案 3 :(得分:0)

USE tempdb
GO  
 DROP TABLE test1
 CREATE TABLE test1(a NVARCHAR(10), ino INT, datebought INT)
INSERT INTO dbo.test1
        ( a, ino, datebought )
VALUES  ( 'a' ,          1    ,        20160101)
INSERT INTO dbo.test1
        ( a, ino, datebought )
VALUES  ( 'b' ,          2    ,        20160202)

INSERT INTO dbo.test1
        ( a, ino, datebought )
VALUES  ( 'c' ,          3    ,        20160903)

INSERT INTO dbo.test1
        ( a, ino, datebought )
VALUES  ( 'd' ,          4   ,        20160101)

SELECT * FROM dbo.test1

SELECT a, COUNT(ino) OVER(PARTITION  BY a) FROM dbo.test1
WHERE datebought>=20160202
UNION ALL
SELECT a,  0 FROM dbo.test1
WHERE datebought<20160202
ORDER BY a