我有一张表“Postings”
CREATE TABLE POSTINGS(
Account_FK INT,
Department_FK INT,
Project_FK INT,
Company_FK INT,
Year INT,
Month INT,
Amount float,
Handled BIT
)
我试图制作一个选择语句,它将每个月为每家公司选择金额总和。 像这样:
SELECT Company_FK, Year, Month, Sum(Amount)
FROM Postings
GROUP BY Company_FK, Year, Month
但我只需要尚未处理的行。例如。 Handled = 0
的行SELECT Company_FK, Year, Month, Sum(Amount)
FROM Postings
WHERE Handled = 0
GROUP BY Company_FK, Year, Month
现在,此查询将仅汇总公司每年和每月的Handled = 0行。 但我还需要总和来包括公司的所有其他行。我的意思是,如果公司中的一行没有得到处理。我需要返回所有公司行的公司总和。
因此,如果Company_FK = 1有三个帖子。所有这些都处理= 1.然后这家公司可以被忽略。但如果Company_FK = 2有三个帖子。其中一个处理= 0,然后我需要返回所有三行的总和。
你明白我的意思吗?
有什么建议吗?
答案 0 :(得分:3)
试试这个:
SELECT distinct c.Company_FK, c.Year, c.Month, b.Amount FROM Postings c
INNER JOIN
(SELECT Company_FK, Year, Month, Sum(Amount) as 'Amount'
FROM Postings
GROUP BY Company_FK, Year, Month) b ON c.Company_FK = b.Company_FK and c.Year = b.Year and c.Month = b.Month
WHERE c.Handled = 0
答案 1 :(得分:1)
您可以在HAVING
GROUP BY
语句
HAVING COUNT(*) > SUM(CONVERT(INT, Handled))
您还需要删除WHERE
子句,因为HAVING
将是过滤器
完整查询:
SELECT Company_FK, Year, Month, Sum(Amount)
FROM Postings
GROUP BY Company_FK, Year, Month
HAVING COUNT(*) > SUM(CONVERT(INT, Handled))
答案 2 :(得分:1)
SELECT Company_FK, Year, Month, Sum(Amount) as "Amount"
FROM Postings
GROUP BY Company_FK, Year, Month
HAVING COUNT(*) > SUM(CONVERT(INT, Handled))
答案 3 :(得分:1)
SELECT Company_FK, Year, Month, Sum(Amount)
FROM Postings p
WHERE Exists (select top 1 1 from Postings po where p.company_fk=po.company_fk and Handled=0 )
GROUP BY Company_FK, Year, Month