我有两张桌子:
T1:
ID Department ATTRIBUTES TEAM
--- ---------- ---------- ------
1 R&D Dress_Code NULL
2 R&D Dress_Code Web
3 R&D Food System
4 R&D Food NULL
5 R&D Color NULL
6 Marketing Food System
T2:
ID VAL
--- ----------
1 Smart
2 Casual
3 Beef
4 Chicken
5 Green
6 Fish
T1的目的是显示所有部门属性。
如果TEAM为null,则适用于该部门的每个人。有时团队会有特殊设置覆盖通用设置。
例如,我希望将设置作为R& D中的“Web”团队。
我可以写:
SELECT T1.DEPARTMENT, T1.ATTRIBUTES, T1.TEAM, T2.VAL
FROM T1
LEFT JOIN T2 ON T1.ID = T2.ID
WHERE T1.DEPARTMENT = 'R&D' AND T1.TEAM = 'Web'
这将显示一条记录,其中着装要求是随意的。
但我希望结果是:
ATTRIBUTES VAL
---------- ------
Dress_Code Casual
Food Chicken
Color Green
同样对于R& D的“系统”团队来说,结果将是智能着装,牛肉和绿色。
我想首先选择所有R& D结果,然后用上面的选择结果替换行。
我需要将其写为存储过程。
非常感谢任何帮助!
答案 0 :(得分:1)
使用CTE和row_number():
with CTE as(
select
ATTRIBUTES,
VAL,
T1.TEAM,
row_number() over (partition by ATTRIBUTES order by team desc) rn
from t1 t1
inner join t2 t2 on t1.ID =t2.ID
AND ( T1.TEAM = 'Web' or T1.TEAM is null )
)
select
ATTRIBUTES ,
VAL
from cte where rn=1
order by val
OutPut:
答案 1 :(得分:0)
SELECT
T1.DEPARTMENT,
T1.ATTRIBUTES,
T1.TEAM,
T2.VAL
INTO #temp
FROM T1
INNER JOIN T2 ON T1.ID = T2.ID
WHERE T1.TEAM is NULL
SELECT
T1.ATTRIBUTES,
T2.VAL
INTO #t2
FROM T1
INNER JOIN T2 ON T1.ID = T2.ID
WHERE T1.TEAM = 'Web'
UPDATE t
SET t.VAL=b.VAL
FROM #temp t
join #t2 b on b.ATTRIBUTES=t.ATTRIBUTES
SELECT
DEPARTMENT,
ATTRIBUTES,
TEAM,
VAL
FROM #temp
即使这样也会有所帮助。