我在网上搜索过,但没有找到任何完全符合我需要的东西。我有两个非常相似的表,除了一列。以下是表格:
TABLE case_cards
CC_Primary_Num | CC_Num | Fac_ID_Num | Surg_Proc_Num | Fac_Equip_ID_Num |
---------------|--------|------------|---------------|------------------|
1 | 10001 | 1 | 2 | 4 |
2 | 10002 | 2 | 3 | 7 |
3 | 10002 | 2 | 3 | 2 |
4 | 10003 | 5 | 7 | 1 |
TABLE case_cards_prep
CC_Control_Num | CC_Prep_Num | Book_Num | Fac_ID_Num | Surg_Proc_Num | Fac_Equip_ID_Num |
---------------|-------------|----------|------------|---------------|------------------|
1 | 1 | 1 | 1 | 2 | 9 |
2 | 2 | 2 | 2 | 3 | 3 |
3 | 2 | 2 | 2 | 3 | 5 |
4 | 3 | 1 | 1 | 2 | 8 |
是否可以使用Select语句,我可以根据case_cards_prep表中Book_Num的可用性来提取一行或多行,如果是,则为相应Book_Num的最大CC_Prep_Num。如果Book_Num不在case_cards_prep中,请从case_cards表中提取Surg_Proc_Num的记录?我还在学习,这个有点过头了。例如:
IF case_card_prep.Book_Num = 2 然后选择所有行 最大值(CC_Prep_Num)
ELSE选择所有行 其中Surg_Proc_Num = 3
(显然不是mysql语法,但你应该明白......我希望)
结果表
Fac_ID_Num | Surg_Proc_Num | Fac_Equip_ID_Num |
-----------|---------------|------------------|
2 | 3 | 3 |
2 | 3 | 5 |
OR
结果表 - 如果不是case_cards_prep
Fac_ID_Num | Surg_Proc_Num | Fac_Equip_ID_Num |
-----------|---------------|------------------|
5 | 7 | 1 |
答案 0 :(得分:0)
这是你想要的吗?
SELECT Fac_ID_Num, MAX(CC_Prep_Num), Fac_Equip_ID_Num
FROM case_cards_prep
GROUP BY Book_Num
UNION
SELECT Fac_ID_Num, Surg_Proc_Num, Fac_Equip_ID_Num
FROM case_cards
WHERE Fac_ID_Num NOT IN (SELECT Fac_ID_Num FROM case_cards_prep )
答案 1 :(得分:0)
尝试使用以下内容根据您的预订编号选择记录。
--Create Table case_cards (CC_Primary_Num int, CC_Num int, Fac_ID_Num int,
Surg_Proc_Num int, Fac_Equip_ID_Num int)
--Create Table case_cards_prep (CC_Control_Num int, CC_Prep_Num int, Book_Num int, Fac_ID_Num int, Surg_Proc_Num int, Fac_Equip_ID_Num int)
--Delete From case_cards
--Insert Into case_cards
--Select 1, 10001, 1,2,4 Union
--Select 2, 10002, 2,3,7 Union
--Select 3, 10002, 2,3,2 Union
--Select 4, 10003, 5,7,1
--Delete From case_cards_prep
--Insert Into case_cards_prep
--Select 1, 1, 1, 1, 2, 9 Union
--Select 2, 2, 2, 2, 3, 3 Union
--Select 3, 2, 2, 2, 3, 5 Union
--Select 4, 3, 1, 1, 2, 8
Create PROCEDURE dbo.GetCaseCards --Stored Proc
@BookNum int = 0 --This is a Variable
AS
--Declare @BookNum int
Declare @CountBook int
Declare @Max int
--Drop Table #Results
Create Table #Results (Fac_ID_Num int, Surg_Proc_Num int, Fac_Equip_ID_Num int)
Select @CountBook = Count(*) From case_cards_prep Where Book_Num = @BookNum
--Select @CountBook
if(@CountBook > 0)
Begin
Select @Max = Max(Surg_Proc_Num) From case_cards_prep
Insert Into #Results
Select Fac_ID_Num, Surg_Proc_Num, Fac_Equip_ID_Num From case_cards_prep Where Surg_Proc_Num = @Max
End
if(@CountBook = 0)
Begin
Insert Into #Results
Select Fac_ID_Num, Surg_Proc_Num, Fac_Equip_ID_Num From case_cards Where Right(CC_Num,1) = @BookNum
End
Select * From #Results
使用以下方法执行该过程:
Exec GetCaseCards 2
Exec GetCaseCards 3