下面是我的查询,它不返回任何行,这根据数据库记录是正确的。
SELECT CustomerID ,
'Forwarder' AS CustType ,
RForLocation ,
YEAR(ReceivedDate) AS CurrentYear ,
CONVERT(VARCHAR, COUNT(CASE WHEN MONTH(ReceivedDate) = 1 THEN 1
ELSE 0
END)) AS Jan
FROM RootTable
WHERE Customerid = 12742
AND YEAR(ReceivedDate) = 2014
GROUP BY CustomerID ,
RForLocation ,
YEAR(ReceivedDate)
但我的要求是我应该获得一个空行,其中customerId,CustType,CurrentYear和Jan Count为零(0)
以下是我的要求
CustomerId CustType CurrentYear Jan
12742 Forwarder 2014 0
由于 请帮忙
答案 0 :(得分:1)
SELECT CustomerID
,'Forwarder' AS CustType
,RForLocation
,YEAR(ReceivedDate) AS CurrentYear
,ISNULL(
NULLIF(
COUNT(CASE WHEN MONTH(ReceivedDate) = 1 THEN 1 ELSE 0 END)
, 0)
, '')
AS Jan
FROM RootTable
WHERE Customerid = 12742
AND YEAR(ReceivedDate) = 2014
GROUP BY CustomerID ,
RForLocation ,
YEAR(ReceivedDate)
答案 1 :(得分:0)
更改CASE
声明
CONVERT(VARCHAR, CASE WHEN count(MONTH(ReceivedDate) = 1)
THEN count(MONTH(ReceivedDate) = 1)
ELSE 0
end
答案 2 :(得分:0)
SELECT
RootTable.CustomerID ,
'Forwarder' AS CustType ,
RForLocation ,
YEAR(ReceivedDate) AS CurrentYear,
SUB1.MON_COL,
CASE WHEN sub1.CNT IS NULL THEN 0 ELSE sub1.CNT END AS CNT
FROM RootTable
LEFT JOIN
(
SELECT COUNT(1) CNT, CustomerId,MONTH(ReceivedDate) AS MON_COL,YEAR(ReceivedDate) AS YEAR_COL
FROM RootTable
GROUP BY CustomerId,MONTH(ReceivedDate),YEAR(ReceivedDate)
) sub1 ON sub1.CustomerID = RootTable.CustomerId AND MONTH(ReceivedDate) = sub1.MON_COL AND YEAR(ReceivedDate) = sub1.YEAR_COL
WHERE RootTable.CustomerId=2
答案 3 :(得分:0)
无论我能理解什么,请找到脚本和更新的查询,我试过了。
创建表:
Create table RootTable
(CustomerID int,
RForLocation varchar(20),
ReceivedDate datetime)
插入数据:
insert into RootTable
Values(1, 'A', '1-Jan-2013'),
(2, 'A', '1-Feb-2013'),
(3, 'B', '1-Jan-2013'),
(4, 'B', '1-Mar-2013')
查询以获取记录:
SELECT CustomerID ,
'Forwarder' AS CustType ,
RForLocation ,
'2014' AS CurrentYear ,
CONVERT(VARCHAR, COUNT(CASE WHEN MONTH(ReceivedDate) = 1 AND YEAR(ReceivedDate) = 2014 THEN 1
ELSE null
END)) AS Jan
FROM RootTable
WHERE Customerid = 1
GROUP BY CustomerID ,
RForLocation;
因为即使他没有特定年份的记录,我也希望为客户提供记录,但我不需要在where子句中给出日期条件,而是我可以根据年份进行计数,这将给出我需要输出。
希望它有所帮助。