我有查询需要很长时间才能执行
SELECT
cft.ID, cft.Name AS 'CauseArea' , COUNT(DISTINCT e.ID) AS 'Donors',
SUM(CASE WHEN d.DonationType = 1 THEN d.Amount ELSE 0 END) AS 'DonationsForAvarage' ,
SUM(CASE WHEN d.DonationType = 1 THEN d.Amount ELSE 0 END) AS 'EmployeeDonations' ,
SUM(CASE WHEN d.DonationType = 2 THEN d.Amount ELSE 0 END) AS 'MatchedDonations' ,
SUM(CASE WHEN d.DonationType = 1 OR d.DonationType = 2 THEN d.Amount ELSE 0 END) AS 'TotalDonations'
FROM
dbo.Donation d
INNER JOIN
dbo.Employee e ON e.ID = d.Employee
INNER JOIN
CharityProjectDetails cpd ON d.CharityProjectDetails = cpd.ID
INNER JOIN
CharityDetails cd ON cpd.CharityDetails = cd.ID
INNER JOIN
CauseFocusType cft ON cd.CauseFocusType = cft.ID
GROUP BY
cft.ID, cft.Name
所以我注意到DISTINCT
是食客。我想摆脱DISTINCT
- 我该怎么做?
答案 0 :(得分:1)
我使用子查询为捐赠表做了。如果这对您有任何帮助,请检查一下。
SELECT cft.ID
,cft.NAME AS 'CauseArea'
,d.cnt AS 'Donors'
,SUM(CASE
WHEN d.DonationType = 1
THEN d.Amount
ELSE 0
END) AS 'DonationsForAvarage'
,SUM(CASE
WHEN d.DonationType = 1
THEN d.Amount
ELSE 0
END) AS 'EmployeeDonations'
,SUM(CASE
WHEN d.DonationType = 2
THEN d.Amount
ELSE 0
END) AS 'MatchedDonations'
,SUM(CASE
WHEN d.DonationType = 1
OR d.DonationType = 2
THEN d.Amount
ELSE 0
END) AS 'TotalDonations'
FROM (SELECT Employee
,DonationType
,CharityProjectDetails
,Amount
,COUNT(Employee) as cnt
FROM dbo.Donation
GROUP BY Employee
,DonationType
,CharityProjectDetails
,Amount) d
INNER JOIN CharityProjectDetails cpd ON d.CharityProjectDetails = cpd.ID
INNER JOIN CharityDetails cd ON cpd.CharityDetails = cd.ID
INNER JOIN CauseFocusType cft ON cd.CauseFocusType = cft.ID
GROUP BY cft.ID
,cft.NAME
答案 1 :(得分:0)
看起来dbo.Employee上的INNER JOIN不是必需的,因为你已经拥有dbo.Donation中的数据。试试这个:
SELECT cft.ID
,cft.NAME AS 'CauseArea'
,COUNT(DISTINCT d.Employee) AS 'Donors'
,SUM(CASE
WHEN d.DonationType = 1
THEN d.Amount
ELSE 0
END) AS 'DonationsForAvarage'
,SUM(CASE
WHEN d.DonationType = 1
THEN d.Amount
ELSE 0
END) AS 'EmployeeDonations'
,SUM(CASE
WHEN d.DonationType = 2
THEN d.Amount
ELSE 0
END) AS 'MatchedDonations'
,SUM(CASE
WHEN d.DonationType = 1
OR d.DonationType = 2
THEN d.Amount
ELSE 0
END) AS 'TotalDonations'
FROM dbo.Donation d
INNER JOIN CharityProjectDetails cpd ON d.CharityProjectDetails = cpd.ID
INNER JOIN CharityDetails cd ON cpd.CharityDetails = cd.ID
INNER JOIN CauseFocusType cft ON cd.CauseFocusType = cft.ID
GROUP BY cft.ID
,cft.NAME