我在下面有 3 个选择语句,每个语句创建完全相同的计算列,然后我计算该计算列中的所有是和所有否。目前它显示该区域 3 次,旁边有 3 个结果。我希望它显示该区域一次,其中包含 3 个带有总计的新列,所以目前
我有:
region1 computedCol1
region1 computedCol2
region1 computedCol3
region2 computedCol1
region2 computedCol2
region2 computedCol3
我想:
Region1, computedCol1, computedCol2, computedCol3
Region2, computedCol1, computedCol2, computedCol3
Region3, computedCol1, computedCol2, computedCol3
如果我使用“union all”,我会得到:
region1 computedCol1
region2 computedCol1
region3 computedCol1
SELECT a.region, COUNT(*) AS [computedCol1]
(
SELECT DISTINCT table1.serial1, table1.serial2, region,
CASE WHEN table2.serial1 IS NULL THEN 'No' ELSE 'Yes' END AS [computedCol1],
CASE WHEN table3.serial2 IS NULL THEN 'No' ELSE 'Yes' END AS [computedCol2],
CASE WHEN table3.serial2 IS NULL AND table2.serial1 IS NULL THEN 'No' ELSE 'Yes' END AS [computedCol3]
FROM table1
LEFT JOIN table2
ON table2.serial1 = table1.serial1
LEFT JOIN dbo.EPG
table3.serial2 = table1.serial2
)a
WHERE region in (
'37000','38000','39000','41000','42000','43000','44000','46000','45000','51000','52000','53000','54000',
'55000','56000','57000','58000','59000','61000','62000','63000','64000','65000','66000','67000','68000',
'69000','30000','33000','36000','34000','35000','31000','32000','N/A' )
and [CCA Match Org] in ('no')
GROUP BY a.region
union
SELECT b.region, COUNT(*) AS [computedCol2], region
(
SELECT DISTINCT table1.serial1, table1.serial2,
CASE WHEN table2.serial1 IS NULL THEN 'No' ELSE 'Yes' END AS [computedCol1],
CASE WHEN table3.serial2 IS NULL THEN 'No' ELSE 'Yes' END AS [computedCol2],
CASE WHEN table3.serial2 IS NULL AND table2.serial1 IS NULL THEN 'No' ELSE 'Yes' END AS [computedCol3]
FROM table1
LEFT JOIN table2
ON table2.serial1 = table1.serial1
LEFT JOIN dbo.EPG
table3.serial2 = table1.serial2
)b
WHERE region in (
'37000','38000','39000','41000','42000','43000','44000','46000','45000','51000','52000','53000','54000'
'55000','56000','57000','58000','59000','61000','62000','63000','64000','65000','66000','67000','68000',
'69000','30000','33000','36000','34000','35000','31000','32000','N/A' )
and [CCA Match Org] in ('yes')
group by b.region
union
SELECT c.region, COUNT(*) AS [computedCol3], region
(
SELECT DISTINCT table1.serial1, table1.serial2,
CASE WHEN table2.serial1 IS NULL THEN 'No' ELSE 'Yes' END AS [computedCol1],
CASE WHEN table3.serial2 IS NULL THEN 'No' ELSE 'Yes' END AS [computedCol2],
CASE WHEN table3.serial2 IS NULL AND table2.serial1 IS NULL THEN 'No' ELSE 'Yes' END AS [computedCol3]
FROM table1
LEFT JOIN table2
ON table2.serial1 = table1.serial1
LEFT JOIN dbo.EPG
table3.serial2 = table1.serial2
)c
WHERE region in (
'37000','38000','39000','41000','42000','43000','44000','46000','45000','51000','52000','53000','54000'
'55000','56000','57000','58000','59000','61000','62000','63000','64000','65000','66000','67000','68000',
'69000','30000','33000','36000','34000','35000','31000','32000','N/A' )
and [CCA Match Org] in ('yes', 'no')
group by c.region