所以我有下表例如
|Company Name | Weight | Date |Unique ID|
|:------------|:-------|:-----|:--------|
|ABC |22 |10-3 |1 |
|ABC |22 |10-3 |2 |
|DEF |50 |10-3 |3 |
|DEF |50 |10-3 |4 |
只有当该组的SUM(WEIGHT)为> = 100时,才需要SELECT语句才能显示组。
所以输出应该是:
|Company Name | Weight | Date |Unique ID|
|:------------|:-------|:-----|:--------|
|ABC |22 |10-3 |1 |
|ABC |22 |10-3 |2 |
|DEF |100 |10-3 |GROUP |
目前,我正在尝试以下方法,但收到无效的群组使用
SELECT COMPANY_NAME, DATE,
(CASE WHEN SUM(WEIGHT) >= 100 THEN 'GROUP' ELSE UNIQUE_ID END) AS
GROUP_CRITERIA
FROM TABLE GROUP BY COMPANY_NAME, DATE,
(CASE WHEN SUM(WEIGHT) >= 100 THEN 'GROUP' ELSE UNIQUE_ID END);
答案 0 :(得分:1)
看来你的意思是你想要的总和(权重)< 100应该包含在一个组中。
为此,我在派生表子查询中执行第一个GROUP BY,然后我可以在外部查询的表达式中引用该总和:
SELECT
CASE WHEN TOTAL_WEIGHT >= 100 THEN COMPANY_NAME ELSE 'GROUP' END AS COMPANY_NAME,
DATE,
SUM(TOTAL_WEIGHT) AS TOTAL_WEIGHT
FROM (
SELECT COMPANY_NAME, DATE, SUM(WEIGHT) AS TOTAL_WEIGHT
FROM MyTable
GROUP BY COMPANY_NAME, DATE
) AS T
GROUP BY COMPANY_NAME, DATE;
答案 1 :(得分:0)
我在想这样的事情:
SELECT DISTINCT T1.company_name, IFNULL(T2.weight, T1.weight) AS weight, IFNULL(T2.date, T1.date) AS "date", IF(T2.company_name IS NULL, T1.unique_id, T2.unique_id)
FROM table T1
LEFT OUTER JOIN (
SELECT company_name, `date`, SUM(weight) AS weight
FROM table
GROUP BY company_name
HAVING SUM(weight) >= 100) T2 ON T2.company_name = T1.company_name
答案 2 :(得分:0)
这是一种方式: (最大(日期),因为你没有提到你是如何为小组做的)
SELECT COMPANY_NAME, DATE, WEIGHT, UNIQUE_ID
FROM TABLE
WHERE COMPANY_NAME in
( SELECT COMPANY_NAME FROM
(SELECT COMPANY_NAME, SUM(WEIGHT) FROM TABLE GROUP BY COMPANY_NAME
HAVING SUM(WEIGHT) < 100) u)
UNION
SELECT COMPANY_NAME, MAX(DATE), SUM(WEIGHT), 'GROUP'
FROM TABLE
WHERE COMPANY_NAME not in
( SELECT COMPANY_NAME FROM (SELECT COMPANY_NAME, SUM(WEIGHT) FROM TABLE GROUP BY COMPANY_NAME
HAVING SUM(WEIGHT) < 100) u)
GROUP BY COMPANY_NAME