我有一个City
和StatePopulation
表
CREATE TABLE dbo.City
(
Code INT,
CityName VARCHAR(30)
)
INSERT INTO CITY (CODE, CityName)
select 1, 'Woodside'
union
select 2, 'Sunnyside'
union
select 3, 'Flushing'
union
select 4, 'Elmhurst'
union
select 5, 'ForestHills'
union
select 6, 'Manhattan'
union
select 7, 'Atlanta'
union
select 8, 'Alpharetta'
union
select 9, 'Johns Creek'
CREATE TABLE DBO.CityPopulation
(
StateCode VARCHAR(10),
CityCode INT,
PopulationCount INT
)
INSERT INTO DBO.CityPopulation (StateCode, CityCode, PopulationCount)
SELECT 'NY', 1, 1000
UNION
SELECT 'NY', 2, 1500
UNION
SELECT 'NY', 3, 2500
UNION
SELECT 'NY', 4, 3000
UNION
SELECT 'NY', 5, 3500
UNION
SELECT 'NY', 6, 4000
UNION
SELECT 'GA', 7, 5500
UNION
SELECT 'GA', 8, 1200
UNION
SELECT 'GA', 9, 1900
CREATE TYPE dbo.UDTT_StateType AS TABLE (StateCode VARCHAR(10), CityCode INT)
DECLAR @State dbo.UDTT_StateType
INSERT INTO @State (StateCode, CityCode)
select 'NY', null
union
select 'GA', 8
现在,我需要返回CityPopulation
中UDTT_StateType
和StateCode
上匹配的CityCode
中的值的行,但是当{{1} }为'NY',而StateCode
为空,我需要返回CityCode 1和2的数据
请问有人可以帮我写这个查询吗?
答案 0 :(得分:0)
我能够通过CROSS JOIN解决这个问题。
SELECT cpd.StateCode, cpd.CityCode, cpd.CityName, cpd.PopulationCount
FROM @State AS s
CROSS JOIN (SELECT * FROM CityPopulation AS cp INNER JOIN city AS c ON cp.CityCode = c.Code
WHERE CityCode IN (1,2)) AS cpd
WHERE s.CityCode = cpd.CityCode OR s.CityCode IS NULL
产生以下结果:
答案 1 :(得分:0)
您可以尝试这个;
select c.* from CityPopulation c,@State s where
s.CityCode is null
And c.CityCode in (1,2,3,4,5,6)
And c.StateCode = s.StateCode
Union
select c.* from CityPopulation c,@State s where
c.CityCode =s.CityCode
And c.StateCode = s.StateCode
答案 2 :(得分:-1)
select c.*
from CityPopulation c, State s
where (
(c.StateCode = s.StateCode and c.CityCode = s.CityCode)
OR (s.StateCode = 'NY' and s.CityCode is null and (c.StateCode='NY' and c.CityCode in (1,2)))
)