How do I use another column if two rows in the first column checked are the same?

て烟熏妆下的殇ゞ 提交于 2021-02-15 07:48:28

问题


I have a table that looks something like this:

stones

ID number snumber wt qt
1 a 11.5 13
2 c 4.0 8
3 a a1 1.0 2
4 d 0.5 1
5 b 2.0 4
6 a a2 5.0 1
7 f 3.0 6
8 a a3 5.0 10

How do I select all from stones and if the column number has rows in the column snumber only give results from snumber's rows [otherwise use number]?

I am also trying to incorporate in my previous [working] code that selects all rows in the table that wt >= 2.5 then count all those rows as totalrows:

SELECT inv.*, COUNT(*) OVER() AS totalrows FROM stones inv WHERE wt >= 2.5
  • So from the example above, I'd want to show the following rows c, a2, f and a3 with totalrows = 4:
ID number snumber wt qt totalrows
2 c 4.0 8 4
6 a a2 5.0 1 4
7 f 3.0 6 4
8 a a3 5.0 10 4

Failed Attempt

I tried these, but I'm getting an error with my PHP so I'm assuming there's a problem with the SQL:

1st

SELECT stones.*,
 CASE 
  WHEN x.totalrows > 1 
   THEN stones.snumber
   ELSE stones.number
  END AS numberORsnumber
  FROM stones 
  JOIN (
   SELECT number, COUNT(*) AS totalrows FROM stones
    GROUP BY number
  ) x ON x.number = stones.number
WHERE x.totalrows = 1 OR stones.snumber <> '' AND wt >= 2.5

2nd

SELECT inv.*, COUNT(*) OVER() AS totalrows FROM stones inv 
 CASE 
  WHEN totalrows > 1
   THEN inv.snumber
  ELSE inv.number
 END AS number
WHERE wt >= 2.5

回答1:


The error is at END AS number OR snumber. After you remove OR snumber, there won't be any error but there won't be any result too; against the example data you've provided. Try changing WHERE x.totalrows = 1 AND wt >= 2.5 to WHERE wt >= 2.5 only because you're already doing a CASE expression:

CASE 
        WHEN x.totalrows > 1
            THEN stones.snumber
            ELSE stones.number
        END AS number

So adding WHERE x.totalrows = 1 won't yield anything from the CASE.

Demo fiddle

Update:

Well, after long discussion in comment, I think I got it:

SELECT inv.ID, 
       CASE WHEN inv.snumber <> "" 
            THEN inv.snumber ELSE inv.number 
            END AS numberORSnumber, 
       inv.wt,
       inv.qt,
       COUNT(*) OVER() AS totalrows,
       CASE WHEN inv.number=v.number 
            AND inv.snumber="" THEN 0 ELSE 1 END AS Checking
FROM stones inv 
CROSS JOIN 
(SELECT number FROM stones WHERE snumber <> "" group by number) v
WHERE wt >= 2.5
HAVING Checking <> 0
ORDER BY ID ASC;

I end up adding a CROSS JOIN with a subquery that return number value that have snumber as per OP requirement. Then with that, I use CASE to do the checking and finally use HAVING to filter them out from the checking.

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=40cb88da028a42dc147dc4224154ab05



来源:https://stackoverflow.com/questions/65912042/how-do-i-use-another-column-if-two-rows-in-the-first-column-checked-are-the-same

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!