已经有类似的问题,但我似乎无法让它为我工作。也许是因为我有几张桌子要加入。
无论哪种方式,这是我的查询:
DECLARE @StartDate datetime2, @EndDate datetime2;
SET @StartDate = DateAdd(day, -7, GETDATE());
SET @EndDate = DateAdd(year, 1, GETDATE());
WITH Weeks AS
(
SELECT @StartDate AS WeekDate
UNION ALL
SELECT DATEADD(day, 7, WeekDate)
FROM Weeks
WHERE DATEADD(day, 7, WeekDate) <= @EndDate
)
SELECT WeekDate AS WeekOfSRUs
,ISNULL(COUNT(i.incident_id), 0) AS SRUCount
--,i.incident_id
,ic.inc_cat_sc
FROM Weeks
,incident i
,JPTSYS_WEB_CUST_PROP_CONT
,JPTSYS_WEB_CUST_PROP
,JPTSYS_WEB_LKUP_DATA
,JPTSYS_WEB_LKUP
,JPTSYS_WEB_CUST_PROP_MULT
,inc_cat ic
WHERE (i.INCIDENT_ID=JPTSYS_WEB_CUST_PROP_CONT.ENTITY_ID AND
JPTSYS_WEB_CUST_PROP_CONT.JPTSYS_WEB_CUST_PROP_ID=JPTSYS_WEB_CUST_PROP.JPTSYS_WEB_CUST_PROP_ID AND
JPTSYS_WEB_CUST_PROP_CONT.SINGLE_SEL_VAL_ID=JPTSYS_WEB_LKUP_DATA.JPTSYS_WEB_LKUP_DATA_ID AND
JPTSYS_WEB_CUST_PROP.JPTSYS_WEB_LKUP_ID=JPTSYS_WEB_LKUP.JPTSYS_WEB_LKUP_ID AND
JPTSYS_WEB_LKUP_DATA.JPTSYS_WEB_LKUP_DATA_ID=JPTSYS_WEB_CUST_PROP_MULT.JPTSYS_WEB_LKUP_DATA_ID AND
JPTSYS_WEB_CUST_PROP.JPTSYS_WEB_CUST_PROP_ID =59) AND
(JPTSYS_WEB_CUST_PROP_CONT.DATE_VAL >= WeekDate AND JPTSYS_WEB_CUST_PROP_CONT.DATE_VAL < DATEADD(day, 7, WeekDate)) AND
(inc_cat_sc = 'R1A DESKTOPMIN' OR inc_cat_sc = 'R1B DESKTOPMAJ' OR inc_cat_sc = 'R8A CRTPATCH-DT') AND i.inc_cat_id = ic.inc_cat_id
GROUP BY ic.inc_cat_sc, Weeks.WeekDate
ORDER BY Weeks.WeekDate
结果:
WeekOfSRUs SRUCount inc_cat_sc
2013-01-25 10:06:57.2370000 4 R1A DESKTOPMIN
2013-01-25 10:06:57.2370000 1 R1B DESKTOPMAJ
2013-02-01 10:06:57.2370000 4 R1A DESKTOPMIN
2013-02-08 10:06:57.2370000 2 R1A DESKTOPMIN
2013-02-08 10:06:57.2370000 1 R1B DESKTOPMAJ
2013-02-15 10:06:57.2370000 3 R1A DESKTOPMIN
2013-02-15 10:06:57.2370000 2 R1B DESKTOPMAJ
2013-02-15 10:06:57.2370000 2 R8A CRTPATCH-DT
2013-02-22 10:06:57.2370000 3 R1A DESKTOPMIN
2013-02-22 10:06:57.2370000 4 R1B DESKTOPMAJ
2013-03-01 10:06:57.2370000 5 R1A DESKTOPMIN
2013-03-08 10:06:57.2370000 4 R1A DESKTOPMIN
2013-03-15 10:06:57.2370000 2 R8A CRTPATCH-DT
2013-03-22 10:06:57.2370000 1 R1A DESKTOPMIN
2013-03-29 10:06:57.2370000 1 R1B DESKTOPMAJ
2013-05-03 10:06:57.2370000 1 R1B DESKTOPMAJ
2013-05-10 10:06:57.2370000 1 R1A DESKTOPMIN
至于引用的所有表,这是我们被迫使用的合同产品,无法控制数据库设计/架构。我被告知这些连接对于获取我正在寻找的特定字段是必要的,因为它是安装后添加的自定义字段。
从我上面发布的链接中,我修改了对LEFT JOIN
所有这些表的查询,但我仍然得到相同的结果。
我对中级/高级 SQL 相当陌生,所以请善待。如果我遗漏了任何信息,我很乐意添加它以使其正常工作。
谢谢