在ORDER BY和GROUP BY中使用案例语句

时间:2014-04-17 10:45:29

标签: sql sql-server-2008

对不起家伙另一个noob问题.....

我已经写了下面的声明,但它返回了重复的行,所以我添加了SELECT DISTINCT。

SELECT DISTINCT
cl.contact_number as contact_number,
cl.legacy_number as legacy_number,
c.label_name as name,
cl.date_of_death as date_of_death,

total_donations=case 
WHEN cp.performance = 'DFLT' then sum(cp.value_of_payments) else NULL
end,

total_legacy_donations=case 
WHEN cc.activity = 'LEGACY' then sum(lbr.amount) else NULL
end,

committed_giver=case 
WHEN cc.activity in ('DD1','SO1') then 'Yes' else NULL
end,

volunteer=case 
WHEN cc.activity = 'VOL' then 'Yes' else NULL
end,

major_donor=case 
WHEN fhd.product <> '9106' and sum(fhd.amount) >5000 then 'Yes' else NULL
end,

legacy_category_enquiry=case 
WHEN cc.activity_value = 'E' AND cc.activity = 'LEGACY' then 'E' else NULL
end,

legacy_category_intender=case 
WHEN cc.activity_value = 'I' AND cc.activity = 'LEGACY' then 'I' else NULL
end,

legacy_category_pledged=case 
WHEN cc.activity_value = 'P' AND cc.activity = 'LEGACY' then 'P' else NULL
end,

legacy_category_active=case 
WHEN cc.activity_value = 'A' AND cc.activity = 'LEGACY' then 'A' else NULL
end,

legacy_category_completed=case 
WHEN cc.activity_value = 'C' AND cc.activity = 'LEGACY' then 'C' else NULL
end,

cl.source as source_code,

active_date=case 
WHEN cc.activity_value = 'A' AND cc.activity = 'LEGACY' then cc.valid_from else NULL
end,

days_to_complete=case 
WHEN cc.activity_value = 'A' AND cc.activity = 'LEGACY' then cc.valid_from else NULL
end,

completed_date=case 
WHEN cc.activity_value = 'C' AND cc.activity = 'LEGACY' then cc.valid_from else NULL
end

FROM
contact_legacies cl
INNER JOIN contacts c ON cl.contact_number = c.contact_number
INNER JOIN contact_performances cp on cl.contact_number = cp.contact_number
INNER JOIN contact_categories cc on cl.contact_number = cc.contact_number
INNER JOIN legacy_bequest_receipts lbr on cl.legacy_number = lbr.legacy_number
INNER JOIN financial_history fh on cl.contact_number = fh.contact_number
INNER JOIN financial_history_details fhd on fh.transaction_number = fhd.transaction_number

GROUP BY
cl.contact_number,cl.legacy_number,c.label_name,cl.date_of_death,cc.activity,fhd.product,
cc.activity_value,cl.source,cp.performance,cc.valid_from

ORDER BY
cl.contact_number,cl.legacy_number,c.label_name,cl.date_of_death,sum(cp.value_of_payments),
sum(lbr.amount),cc.activity,fhd.product,cc.activity_value,cl.source

当我运行脚本时,我得到下面的错误,但我不确定我需要添加到GROUP BY子句。我错过了什么?

提前道歉,因为我对这一切都很陌生并且处于最后阶段!

Msg 145, Level 15, State 1, Line 3
ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

0 个答案:

没有答案