2
SELECT ORIGIN_NAME, SUM(NET_WEIGHT),
CASE WHEN ORIGIN_NAME IS NULL THEN 'Basket' ELSE ORIGIN_NAME END AS ORIGIN
FROM VW_PURCHASE_ORDER
GROUP BY ORIGIN_NAME

我有上面的查询,我在饼图中使用。

但是,由于此查询从中获取的信息具有重复记录,因此我需要进行上述查询:(尽管我确定 WHERE 是错误的,因为它缺少完成子句的适当表达式)

WHERE DISTINCT PO_PREFIX||PO_NUMBER||PO_SUFFIX

所以我不会重复计算重复记录中的权重

我已经尝试过子查询,但我目前是 SQL 编程的一个相当大的新手,而且我认为我没有正确执行它们(可以将 SELECT DISTINCT 列用作子查询吗?)。

4

3 回答 3

5

让我们将操作分解为步骤,

步骤 1. 查找所有不同的行:

SELECT DISTINCT 
   PO_PREFIX, PO_NUMBER, PO_SUFFIX, NET_WEIGHT,
   COALESCE(ORIGIN_NAME, 'Basket') AS ORIGIN
FROM 
   VW_PURCHASE_ORDER ;

第 2 步:按 分组origin,使用上述作为派生表(名为tmp):

SELECT
   ORIGIN, SUM(NET_WEIGHT) AS SUM_NET_WEIGHT
FROM
   ( SELECT DISTINCT 
        PO_PREFIX, PO_NUMBER, PO_SUFFIX, NET_WEIGHT,
        COALESCE(ORIGIN_NAME, 'Basket') AS ORIGIN
     FROM 
        VW_PURCHASE_ORDER 
   ) tmp
GROUP BY
   ORIGIN ;
于 2013-01-11T09:32:37.550 回答
0

我认为您想要的是首先选择所有不同的行,然后按您的分组。所以这个查询可能会做你需要的:

SELECT ORIGIN, SUM(NET_WEIGHT)
FROM (
SELECT DISTINCT 
* ,
CASE WHEN ORIGIN_NAME IS NULL THEN 'Basket' ELSE ORIGIN_NAME END AS ORIGIN
FROM VW_PURCHASE_ORDER) AS QUERY
GROUP BY ORIGIN
于 2013-01-11T09:22:21.207 回答
0

我认为这会对您有所帮助

SELECT TOP 1 ORIGIN_NAME, SUM(NET_WEIGHT),
CASE WHEN ORIGIN_NAME IS NULL THEN 'Basket' ELSE ORIGIN_NAME END AS ORIGIN
FROM VW_PURCHASE_ORDER
GROUP BY ORIGIN_NAME
于 2013-01-11T09:12:46.157 回答