SQL组合键查询

时间:2009-02-10 11:49:04

标签: sql aggregate-functions composite-key

再次引用此SQL products/productsales

当主键由两列而不是一列组成时,我怎么能这样做呢?

所以产品有两列作为PK,而productsales有两列作为FK。

这是一个带有1列密钥的解决方案:

SELECT p.[name]
FROM products p
WHERE p.product_id in (SELECT s.product_id
    FROM productsales s
    WHERE s.[date] between @dateStart and @dateEnd
    GROUP BY s.product_id
    HAVING Sum(s.quantity) > @X )

6 个答案:

答案 0 :(得分:3)

这些方面的某些方法可以起作用

SELECT p.[name]
FROM products p
JOIN (SELECT s.key1, s.key2
    FROM productsales s
    WHERE s.[date] between @dateStart and @dateEnd
    GROUP BY s.product_id
    HAVING Sum(s.quantity) > @X ) as a on a.key1 = p.key1 and a.key2 = p.key2 

答案 1 :(得分:2)

也许这样的事情可以做到:

SELECT p.first_col_id,p.second_col_id 
FROM products p
JOIN productsales s
   ON s.first_col_id = p.first_col_id 
  AND s.second_col_id = p.second_col_id 
  AND s.[date] between @dateStart and @dateEnd
GROUP BY p.first_col_id,p.second_col_id 
HAVING Sum(s.quantity) > @X )

答案 2 :(得分:2)

看起来上面有几个答案可行,但只是为了给你另一个解决方案,以防你的情况更好:

SELECT
     P.name
FROM
     Products P
WHERE
     EXISTS
     (
          SELECT
               *
          FROM
               ProductSales PS
          WHERE
               PS.product_id = P.product_id AND
               PS.date BETWEEN @date_start AND @date_end
          GROUP BY
               PS.product_id
          HAVING
               SUM(PS.quantity) > @cutoff_quantity
     )

使用Brownstone先生给出的GROUP BY方法,这种方法的表现往往比INNER JOIN差,但在某些情况下,取决于你的@cutoff_quantity值和表格大小,它可以表现得更好。

答案 3 :(得分:1)

尝试:

SELECT p.[name]
FROM products p
WHERE (p.product_key1, p.product_key2) in
   (SELECT s.product_key1, s.product_key2
    FROM productsales s
    WHERE s.[date] between @dateStart and @dateEnd
    GROUP BY s.product_key1, s.product_key2
    HAVING Sum(s.quantity) > @X )

答案 4 :(得分:1)

我喜欢这样做:

;WITH t 
     AS (SELECT s.product_id 
         FROM   productsales s 
         WHERE  s.[date] BETWEEN @dateStart AND @dateEnd 
         GROUP  BY s.product_id 
         HAVING Sum(s.quantity) > @X) 
SELECT p.[name] 
FROM   products p 
       JOIN t 
         ON p.pk1 = t.fk1 
            AND p.pk2 = t.fk2 

答案 5 :(得分:0)

用一个键重构

SELECT s.product_id, p.[name]
FROM products p JOIN productsales s ON p.product_id=s.product_id
WHERE s.[date] between @dateStart and @dateEnd
GROUP BY s.product_id, p.[name]
HAVING Sum(s.quantity) > @X )

两个键相同:

SELECT s.k1, s.k2, p.[name]
FROM products p JOIN productsales s ON (p.k1=s.k1 AND p.k2=s. k2)
WHERE s.[date] between @dateStart and @dateEnd
GROUP BY s.k1, s.k2, p.[name]
HAVING Sum(s.quantity) > @X )