我有這個查詢可以爲我返回正確的結果。從postgres中的同一查詢中提取出「水平」列中的「年份」列和「顯示年份」列sql
SELECT distinct(companies.name),
date_part('year', scopes.time_stamp) as fy,
count(def.dp_code)as answ_count
FROM companies companies,
scopes scopes,
values dp,
definition def,
content cd
where scopes.company_id = companies.company_id
and scopes.scope_id=dp.scope_id
and dp.content_id=cd.definition_id
and def.definition_id=cd.definition_id
group by companies.name, date_part('year',scopes.time_stamp)
ORDER BY companies.name
以下是上述查詢的結果。
name fy count
3M Co 2002 200
3M Co 2003 100
3M Co 2004 150
3M Co 2005 160
3M Co 2006 169
AB SKF 2002 212
AB SKF 2003 214
AB SKF 2004 215
AB SKF 2005 237
AB SKF 2006 456
3i Group plc 2002 546
3i Group plc 2003 214
3i Group plc 2004 215
3i Group plc 2005 237
3i Group plc 2006 456
我需要水平顯示的結果是這樣的:
name 2002 2003 2004 2005 2006
3M Co 200 100 150 160 169
AB SKF
3i Group plc 546 214 215 237 456
修改後的查詢,但我沒有得到正確的count.I不知道如何計算ans_count.Please幫我這一點。
SELECT
distinct(companies.name),
count(CASE WHEN date_part('year', scopes.time_stamp) = 2002 THEN answ_count end) AS Year1,
count(CASE WHEN date_part('year', scopes.time_stamp) = 2003 THEN answ_count end) AS Year2,
count(CASE WHEN date_part('year', scopes.time_stamp) = 2004 THEN answ_count end) AS Year3,
count(CASE WHEN date_part('year', scopes.time_stamp) = 2005 THEN answ_count end) AS Year4,
count(CASE WHEN date_part('year', scopes.time_stamp) = 2006 THEN answ_count end) AS Year5,
count(CASE WHEN date_part('year',scopes.time_stamp) = 2007 THEN answ_count end) AS Year6,
count(CASE WHEN date_part('year', scopes.time_stamp) = 2008 THEN answ_count end) AS Year7,
count(CASE WHEN date_part('year', scopes.time_stamp) = 2009 THEN answ_count end) AS Year8,
count(CASE WHEN date_part('year', scopes.time_stamp) = 2010 THEN answ_count end) AS Year9,
count(CASE WHEN date_part('year', scopes.time_stamp) = 2011 THEN answ_count end) AS Year10,
count(CASE WHEN date_part('year', scopes.time_stamp) = 2012 THEN answ_count end) AS Year11,
count(CASE WHEN date_part('year', scopes.time_stamp) = 2013 THEN answ_count end) AS Year12,
count(CASE WHEN date_part('year', scopes.time_stamp) = 2014 THEN answ_count end) AS Year13,
count(CASE WHEN date_part('year', scopes.time_stamp) = 2015 THEN answ_count end) AS Year14,
count(CASE WHEN date_part('year', scopes.time_stamp) = 2016 THEN answ_count end) AS Year16
FROM
companies companies,value_scopes value_scopes,dp_values dp,dp_definition def,dp_content_definition cd
where
value_scopes.company_id = companies.company_id
and value_scopes.value_scope_id=dp.value_scope_id
and dp.dp_content_definition_id=cd.dp_content_definition_id
and def.dp_definition_id=cd.dp_definition_id
and value_scopes.is_partial='f'
group by companies.name
ORDER BY companies.name;
DISTINCT不是一個函數(上欄),它是'選擇DISTINCT'的一部分,作品在整個選定的行上。 I.e'SELECT distinct(c1),c2' eq'SELECT DISTINCT c1,c2' eq'SELECT DISTINCT c1,(c2)'。 – jarlh
切換到現代,明確的JOIN語法。易於編寫(沒有錯誤),更易於閱讀(和維護),並且在需要時更容易轉換爲外部聯接。 – jarlh
欣賞你的建議...我不知道如何形成這樣的顯示查詢.. – SUDARSHAN