我正在使用SQL Server 2005.我正在尝试收集有关3个不同表的信息。
表1为 [User_Table] ,如下所示:
Lead ID
1 5
1 8
1 12
2 13
2 14
2 15
2 18
2 24
表2是 [相互作用] ,如下所示:
Int_Date ID Interaction
2012-03-01 5 Hang Up
2012-03-01 13 Reset
2012-03-01 8 Basic
2012-03-01 13 Basic
2012-03-02 14 Reset
2012-03-02 12 Advanced
2012-03-02 12 Hang Up
2012-03-02 24 Reset
2012-03-02 5 Basic
表3是 [重复] ,看起来像是:
Repeat_d ID R_Interaction
2012-03-01 13 Reset
2012-03-01 8 Basic
2012-03-02 14 Reset
2012-03-02 12 Advanced
2012-03-02 24 Reset
我需要做的是将来自[交互]的总调用量作为每个交互类型和日期的总和,并按引导和Int_Date = Repeat_d
对它们进行分组我希望结果如何:
DATE Lead Total_Interactions Total_Repeats Interaction
2012-03-01 1 1 0 Hang Up
2012-03-01 1 2 1 Basic
2012-03-01 2 1 1 Reset
2012-03-01 2 1 0 Basic
2012-03-02 1 1 1 Advanced
2012-03-02 1 1 0 Hang Up
2012-03-02 1 1 0 Basic
2012-03-02 2 2 1 Reset
我的查询到目前为止看起来像:
DECLARE @StartDate smalldatetime, @EndDate smalldatetime, @TL_ID as smallint
SET @StartDate = '20120301'
SET @EndDate = '20120331'
SET @TL_ID = '2'
SELECT
DATEADD(dd, DATEDIFF(dd, 0, [Int_Date]),0) as [Int_Date]
,[Interaction]
,COUNT([Interaction]) as [Total_Repeats]
FROM [Interactions] (NOLOCK)
LEFT JOIN [user_table] (NOLOCK) ON [id] = [id]
WHERE [Int_Date] BETWEEN @StartDate AND @EndDate
AND [Lead] = @TL_ID
GROUP BY DATEADD(dd, DATEDIFF(dd, 0, [Int_Date]),0), [Interaction]
ORDER BY [Int_Date], [Total_Repeats] DESC
非常感谢任何帮助。谢谢!
答案 0 :(得分:0)
尝试以下查询:
DECLARE
@StartDate SMALLDATETIME,
@EndDate SMALLDATETIME,
@TL_ID SMALLINT
SELECT
@StartDate = '2012-03-01',
@EndDate = '2012-03-31',
@TL_ID = '2'
SELECT
DATEADD(DD, DATEDIFF(DD, 0, [Int_Date]), 0) AS [Int_Date],
u.[Lead],
i.[ID],
COUNT(1) + COUNT(r.[ID]) AS [Total_Interactions],
COUNT(r.[ID]) AS [Total_Repeats],
i.[Interaction]
FROM
[Interactions] AS i WITH (NOLOCK)
JOIN
[User_Table] AS u WITH (NOLOCK)
ON
u.[ID] = i.[ID]
LEFT OUTER JOIN
[Repeats] AS r WITH (NOLOCK)
ON
r.[ID] = i.[ID]
AND r.[Repeat_d] = i.[Int_Date]
AND r.[R_Interaction] = i.[Interaction]
WHERE
i.[Int_Date] BETWEEN @StartDate AND @EndDate
AND u.[Lead] = @TL_ID
GROUP BY
DATEADD(DD, DATEDIFF(DD, 0, [Int_Date]), 0),
u.[Lead],
i.[ID],
i.[Interaction]
ORDER BY
[Int_Date],
u.[Lead],
i.[ID],
[Total_Repeats] DESC