我正在尝试为报告制作一个选择语句。我有它拉数据和我需要的一切,但我注意到,因为我必须使用它的组是删除表中不存在的行。如何阻止或使其发挥作用。
SELECT Sum(CASE WHEN direction = 'I' THEN 1 ELSE 0 END) InBound,
Sum(CASE WHEN direction = 'O' THEN 1 ELSE 0 END) OutBound,
Sum(CASE WHEN direction = 'I' THEN p.duration ELSE 0 END) InBoundTime,
Sum(CASE WHEN direction = 'O' THEN p.duration ELSE 0 END) OutBoundTime,
u.fullname,
( CASE
WHEN EXISTS (SELECT g.goalamount
FROM [tblbrokergoals] AS g
WHERE ( g.goaldate BETWEEN
'2016-03-21' AND '2016-03-27' ))
THEN
g.goalamount
ELSE 0
END ) AS GoalAmount
FROM [tblphonelogs] AS p
LEFT JOIN [tblusers] AS u
ON u.fullname = p.phonename
LEFT OUTER JOIN [tblbrokergoals] AS g
ON u.fullname = g.brokername
WHERE ( calldatetime BETWEEN '2016-03-21' AND '2016-03-27' )
AND ( u.userid IS NOT NULL )
AND ( u.direxclude <> '11' )
AND u.termdate IS NULL
AND ( g.goaldate BETWEEN '2016-03-21' AND '2016-03-27' )
GROUP BY u.fullname,
g.goalamount;
当用户在BrokerGoals中时,这可以工作并获取所有数据,但是当用户不在代理目标中时,它只删除返回结果集上的那一行。如果用户不存在于brokergoals表中以将该值设置为0或 - 那么该行不会被删除。如何才能获得它。
答案 0 :(得分:0)
如果您有brokers
表,则可以将其用于left join
SELECT b.broker_id, ....
FROM brokers b
LEFT JOIN .... ALL YOUR OTHER TABLES
....
GROUP BY b.broker_id, ....
如果您的经纪人姓名重复,请使用
SELECT b.broker_id, ....
FROM (SELECT DISTINCT broker_id
FROM brokers) b
LEFT JOIN .... ALL YOUR OTHER TABLES
....
GROUP BY b.broker_id, ....
答案 1 :(得分:0)
SELECT u.FullName,
SUM(CASE WHEN Direction = 'I' THEN 1 ELSE 0 END) AS InBound,
SUM(CASE WHEN Direction = 'O' THEN 1 ELSE 0 END) OutBound,
SUM(CASE WHEN Direction = 'I' THEN p.Duration ELSE 0 END) InBoundTime,
SUM(CASE WHEN Direction = 'O' THEN p.Duration ELSE 0 END) OutBoundTime,
CASE WHEN EXISTS (
SELECT g.GoalAmount
FROM [Portal].[dbo].[tblBrokerGoals] AS g
WHERE g.GoalDate BETWEEN '2016-03-21' AND '2016-03-27'
AND u.FullName = g.BrokerName
) THEN (
SELECT g.GoalAmount
FROM [Portal].[dbo].[tblBrokerGoals] AS g
WHERE g.GoalDate BETWEEN '2016-03-21' AND '2016-03-27'
AND u.FullName = g.BrokerName
) ELSE '0' END AS GoalAmount
FROM [Portal].[dbo].[tblUsers] AS u
LEFT JOIN [Portal].[dbo].[tblPhoneLogs] AS p
ON u.FullName = p.PhoneName
WHERE u.UserID IS NOT NULL
AND u.DirExclude <> '11'
AND u.TermDate IS NULL
AND p.CallDateTime BETWEEN '2016-03-21' AND '2016-03-27'
GROUP BY u.FullName
这就是我最终要解决的问题。我添加了Case When Exists语句,然后在then语句中选择了else,它是0。
答案 2 :(得分:0)
你有没有尝试过更换(CASE 什么时候出现(选择g.goalamount 来自[tblbrokergoals] AS g 在哪里(g.goaldate BETWEEN &#39; 2016年3月21日&#39; AND&#39; 2016-03-27&#39; )) 然后 g.goalamount ELSE 0 END)作为GoalAmount 到g.goalamount,因为你已经在where子句
中有了这个日期条件