SQL - 将另一个SELECT查询与JOIN

时间:2015-09-30 23:28:49

标签: sql-server tsql join where-clause with-statement

我在stackoverflow上发现了这篇文章,Add a summary row with totals

我想要完成的只是那个,但是我在下面的WITH语句中列出了转换后的DURATION字段。我试图将当天的持续时间列(24小时)整理一下。我不知道它是否可能。让我知道。谢谢!

;WITH dupes AS
(
    SELECT 
        CALLER_PHONE, DIALED_PHONE
    FROM 
        dbo.PBXDATA
    GROUP BY 
        CALLER_PHONE, DIALED_PHONE
)
SELECT 
    c.CALL_TIME, c.SALES_REP, c.CALL_TYPE, c.FLAG1, 
    COALESCE(NULLIF(c.FLAG3, 'NULL'),'') AS FLAG3, 
    ISNULL(dupes.CALLER_PHONE, '') + ISNULL(dupes.DIALED_PHONE,'') AS PHONE, 
    CONVERT(VARCHAR(8), c.DURATION, 108) AS DURATION
FROM 
    dupes
JOIN 
    dbo.PBXDATA c ON dupes.CALLER_PHONE = c.CALLER_PHONE 
                  OR dupes.DIALED_PHONE = c.DIALED_PHONE
WHERE 
    (c.SALES_REP LIKE 'Doug%' OR 
     c.SALES_REP LIKE 'Nick%' OR 
     c.SALES_REP LIKE 'Bob%' OR 
     c.SALES_REP LIKE 'Joe%' OR 
     c.SALES_REP LIKE 'John%')
    AND (c.CALL_TIME >= DATEADD(DAY, 0, DATEDIFF(DAY, 0,   CURRENT_TIMESTAMP)))
    AND (c.CALL_TIME <  DATEADD(DAY, 1, DATEDIFF(DAY, 0,  CURRENT_TIMESTAMP)))
    AND DURATION = (SELECT CAST(DATEADD(S, SUM(DATEDIFF(S, '00:00:00', DURATION)), '00:00:00') AS TIME) 
                    FROM dbo.PBXDATA) 
ORDER BY 
    c.CALL_TIME;

1 个答案:

答案 0 :(得分:0)

如果您只想在欺骗表格中获得持续时间的总计,那么您可以将持续时间加在那里。

;WITH dupes AS
(
SELECT CALLER_PHONE, DIALED_PHONE, convert(varchar(8), SUM(c.DURATION), 108) AS Total_Time 
FROM dbo.PBXDATA
GROUP BY CALLER_PHONE, DIALED_PHONE
)

,Total_Time 添加到SELECT语句中。

如果您的查询中有多天,则需要在欺骗中添加日期字段,并将其添加为JOIN ON 的一部分子句。