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列用作子查询吗?)。
答案 0 :(得分: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 ;
答案 1 :(得分: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
答案 2 :(得分: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