driverphone| drivername|guarantor1_phone|guarantor2_phone
---------------------------------------------------------
0801 |Mr A |0803 |0802
0802 |Mr B |0804 |0801
0803 |Mr C |0805 |0801
0804 |Mr D |0802 |0805
0805 |Mr E |0801 |0803
我想在SQL Server中获取此结果集
driverphone| drivername|Total Guaranteed
----------------------------------------
0801 |Mr A | 3
0802 |Mr B | 2
0803 |Mr C | 2
0804 |Mr D | 1
0805 |Mr E | 2
即选择每个驱动程序保证的总数。 driver->担保人关系基于电话号码。
答案 0 :(得分:2)
对两个担保人列进行LEFT JOIN并对其进行明确计算。
<强>架构:强>
CREATE TABLE #TAB (
driverphone VARCHAR(10)
,drivername VARCHAR(10)
,guarantor1_phone VARCHAR(10)
,guarantor2_phone VARCHAR(10)
)
INSERT INTO #TAB
SELECT '0801',' Mr A', '0803', '0802'
UNION ALL
SELECT '0802',' Mr B', '0804', '0801'
UNION ALL
SELECT '0803',' Mr C', '0805', '0801'
UNION ALL
SELECT '0804',' Mr D', '0802', '0805'
UNION ALL
SELECT '0805',' Mr E', '0801', '0803'
现在选择如下所示
SELECT T.driverphone
,T.drivername
,COUNT(DISTINCT T2.driverphone) + COUNT(DISTINCT T3.driverphone)
FROM #TAB T
LEFT JOIN #TAB T2 ON T.driverphone = T2.guarantor1_phone
LEFT JOIN #TAB T3 ON T.driverphone = T3.guarantor2_phone
GROUP BY T.driverphone
,T.drivername
结果将是
+-------------+------------+------------------+
| driverphone | drivername | (No column name) |
+-------------+------------+------------------+
| 0801 | Mr A | 3 |
| 0802 | Mr B | 2 |
| 0803 | Mr C | 2 |
| 0804 | Mr D | 1 |
| 0805 | Mr E | 2 |
+-------------+------------+------------------+
答案 1 :(得分:1)
我认为最简单的方法是outer apply
:
select t.driverphone, t.drivername, g.totalguaranteed
from t outer apply
(select count(*) as totalguaranteed
from (values (guarantor1_phone), (guarantor2_phone)) v(guarantor)
where v.guarantor = t.driverphone
) g;