根据以下条件创建select语句(SQL SERVER)的以下问题,寻找一些关于我应该考虑哪些选项的方向:
注意:简化实际问题
如果我有两个表,每个表都有一个我需要使用的字段 示例:
CUSTOMER.CUSTOMER_ID
PRODUCT.PRODUCT_ID
我还有另外两张表,根据这两个字段保存特殊产品定价 实施例:
CUSTOMER_PRICING
***************************************
* CUSTOMER_ID * PRODUCT_ID * PRICE *
* *
* ABC * 100 * 5.00 *
***************************************
MARKET_PRICING
***************************************
* CUSTOMER_ID * PRODUCT_ID * PRICE *
* *
* ACME * 200 * 7.00 *
***************************************
对于每个CUSTOMER.CUSTOMER_ID和PRODUCT.PRODUCT_ID,我想使用左外连接加入CUSTOMER_PRICING和MARKET_PRICING记录。但条件仅适用于
A)PRICE字段不为空
B)如果两者都存在CUSTOMER_ID / PRODUCT_ID,我只想要来自CUSTOMER_PRICE的记录
类似的东西:
IF EXISTS (SELECT C.CUSTOMER_ID, P.PRODUCT_ID FROM CUSTOMER C, PRODUCT P
WHERE C.CUSTOMER_ID, P.PRODUCT_ID IN
(SELECT PRICE FROM CUSTOMER_PRICE WHERE PRICE IS NOT NULL))
ELSE IF EXISTS
(SELECT C.CUSTOMER_ID, P.PRODUCT_ID FROM CUSTOMER C, PRODUCT P
WHERE C.CUSTOMER_ID, P.PRODUCT_ID IN
(SELECT PRICE FROM MARKET_PRICE WHERE PRICE IS NOT NULL))
***然后以某种方式加入这些结果......
任何建议?
答案 0 :(得分:1)
我想我已经找到了解决方案。我确信SQL专家可以提供更好的东西,但这应该让你感动:
WITH CTE AS
(
SELECT C.CUSTOMER_ID, C.PRODUCT_ID, C.CUSTOMER_PRICE as [PRICE], 1 as [T]
FROM CUSTOMER_PRICE C WHERE C.CUSTOMER_PRICE IS NOT NULL
UNION
SELECT P.CUSTOMER_ID, P.PRODUCT_ID,P.MARKET_PRICE as [PRICE], 2 as [T]
FROM MARKET_PRICE P WHERE P.MARKET_PRICE IS NOT NULL
)
select CUSTOMER_ID,PRODUCT_ID,
(
SELECT TOP (1) PRICE FROM CTE i WHERE i.CUSTOMER_ID = o.CUSTOMER_ID AND i.PRODUCT_ID = o.PRODUCT_ID
ORDER BY T
) as [PRICE]
from CTE o
GROUP BY CUSTOMER_ID,PRODUCT_ID
这将为您提供客户ID,产品ID和价格的明确列表;赞成CUSTOMER_PRICE
价格。
修改的 这仅适用于SQL数据库2008及更高版本。它利用Common Table Expressions作为2008年的新构造。
更新 修复了where子句。
答案 1 :(得分:1)
您可以加入CUSTOMER
和PRODUCT
与[{1}}和CUSTOMER_PRICING
的交叉产品,过滤掉MARKET_PRICING
和{{{ 1}}是NULL。它可能看起来像这样:
CUSTOMER_PRICING.PRICE
答案 2 :(得分:1)
CREATE VIEW CMPricing
AS
SELECT
t1.CUSTOMER_ID,
t1.PRODUCT_ID,
t1.PRICE AS CUSTOMER_PRICE
t2.PRICE AS MARKET_PRICE
FROM CUSTOMER_PRICING t1
INNER JOIN MARKET_PRICING t2
ON t1.CUSTOMER_ID = t2.CUSTOMER_ID
AND t1.PRODUCT_ID = t2.PRODUCT_ID
WHERE t1.PRICE IS NOT NULL
AND t2.PRICE IS NOT NULL
然后查询此视图以获得所需内容。
此视图仅包含“PRICE”表之间通用的数据,其中“PRICE”值均不为空。这个视图本质上是为您进行过滤,这反过来使您对其他数据表的查询更容易理解。
答案 3 :(得分:0)
如果您使用的是ORACLE,则应使用union来消除重复的行并进行2次单独的查询。