我正在嘗試將一行(公司名稱)轉換為多列,并為每個公司顯示真/假,指示某個檔案是否是自動化的。
當前查詢:
select distinct
company.NAME as Company_Name, at.templateid as Template_ID,
doctemp.templatename as Template_Name,
case
when at.activeind = 0 then 'False'
when at.activeind > 0 then 'True'
end as Automation_Enabled
from
opcoautomatedtemplate at
left join
cctl_operatingcompany company on company.ID = at.operatingcompany
left join
doctemplate doctemp on at.templateid = doctemp.templateid
當前查詢結果:
Company_Name | Template_ID | Template_Name | Automation_Enabled
---------------------------------------------------------------
CompanyA | 1 | Document A | True
CompanyB | 1 | Document A | True
CompanyA | 2 | Document B | False
CompanyB | 2 | Document B | True
CompanyA | 3 | Document C | False
CompanyB | 3 | Document C | False
期望的結果:
Template_ID | Template_Name | CompanyA | CompanyB
-------------------------------------------------
1 | Document A | True | True
2 | Document B | False | True
3 | Document C | False | False
實際上有 7 家不同的公司,我們檢查了 600 多個檔案,因此當前的結果瀏覽起來有點麻煩。此外,我們在 Oracle 中運行我們的查詢,這可能比 SQL Server 更溫和一些。我對 SQL 有點陌生,因此感謝您的幫助!
uj5u.com熱心網友回復:
您可以通過使用來實作這一點PIVOT,例如:
WITH company_dets AS (SELECT 'CompanyA' company_name, 1 template_id, 'Document A' template_name, 1 activeind FROM dual UNION ALL
SELECT 'CompanyB' company_name, 1 template_id, 'Document A' template_name, 3 activeind FROM dual UNION ALL
SELECT 'CompanyA' company_name, 2 template_id, 'Document B' template_name, 0 activeind FROM dual UNION ALL
SELECT 'CompanyB' company_name, 2 template_id, 'Document B' template_name, 2 activeind FROM dual UNION ALL
SELECT 'CompanyA' company_name, 3 template_id, 'Document C' template_name, 0 activeind FROM dual UNION ALL
SELECT 'CompanyB' company_name, 3 template_id, 'Document C' template_name, 0 activeind FROM dual)
-- end of mimicking your data set in order to demo the pivot query
SELECT template_id,
template_name,
"CompanyA",
"CompanyB"
FROM (SELECT company_name,
template_id,
template_name,
CASE WHEN activeind = 0 THEN 'False'
WHEN activeind > 0 THEN 'True'
END automation_enabled
FROM company_dets) -- your query to generate the resultset to pivot would go in here
PIVOT (MAX(automation_enabled) FOR (company_name) IN ('CompanyA' AS "CompanyA", 'CompanyB' AS "CompanyB"));
TEMPLATE_ID TEMPLATE_NAME CompanyA CompanyB
----------- ------------- -------- --------
1 Document A True True
2 Document B False True
3 Document C False False
請注意,pivot 使用聚合函式來派生資料 - 我假設在您的資料中,如果您要為同一家公司獲取兩行,模板 ID 和模板名稱,但它們的自動化狀態不同,您會想要將行合并為一個并報告 True 而不是 False。如果要回傳 False 而不是 True,請使用MIN而不是MAX
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/442068.html
上一篇:如何根據日期PIVOT列
下一篇:ORACLE:函式
