SQL对列1进行排序并在第2列中添加所有值

时间:2017-04-27 08:32:29

标签: sql sql-server

我有一个查询,它会返回一组结果,显示货架位置以及是否正在使用货架。货架布局如:" A1XXX01,A1XXX02"然后转到A2等等。下面的屏幕截图显示了我目前正在返回的结果集,我想以这样的方式对数据进行排序:

location   amountUsed   amountFree
   A1          200          100
   A2          100          500
   B1          520          100

这是我到目前为止的查询以及它返回的一小段数据的屏幕截图

SELECT 
wl.location,
CASE WHEN COALESCE(SUM(quantity), 0) = 0 THEN 0 ELSE 1 END as isUsed
FROM warehouse_locations as wl LEFT JOIN
     product_stock_warehouse as psw
     ON psw.location = wl.location 
WHERE wl.unitId_unitId LIKE '1'
GROUP BY wl.location 
order by wl.location

enter image description here

" isUsed" column为1表示货架正在使用,0表示货架正在使用

3 个答案:

答案 0 :(得分:4)

SELECT 
LEFT(wl.location,2) as shelf,
SUM(CASE WHEN COALESCE(SUM(quantity), 0) = 0 THEN 0 ELSE 1 END) as isUsed,
SUM(CASE WHEN COALESCE(SUM(quantity), 0) = 0 THEN 1 ELSE 0 END) as isNotUsed

FROM warehouse_locations as wl LEFT JOIN
     product_stock_warehouse as psw
     ON psw.location = wl.location 
WHERE wl.unitId_unitId LIKE '1'
GROUP BY LEFT(wl.location,2)
order by LEFT(wl.location,2)

假设货架总是采用双字符格式。

P.S。你可能忘记了这部分的通配符了吗?

wl.unitId_unitId LIKE '1' 如果你没有,那真的就是这样。您可以将其更改为wl.unitId_unitId = '1'

答案 1 :(得分:0)

因此,查看您的问题时,您似乎希望按照' location'的前2个字符对结果进行分组。然后你只需稍微调整一下case语句。这是未经测试的,可能是更好的方法,但我认为这应该或多或少有效。

if {mytable.field} = 'xxx' then
 {mytable.field};

答案 2 :(得分:0)

有人提出了答案,但很快就将其删除并且有效,这是经过一些调整后的工作代码

SELECT  substring(location, 1, 2) as location,
    count(case when isUsed = 1 then location END) as amountUsed,
    count(case when isUsed = 0 then location END) as amountFree,
    count(isUsed) as totalShelves
FROM    (
            SELECT  wl.location,
                    CASE WHEN COALESCE(SUM(quantity), 0) = 0 THEN 0 ELSE 1 END as isUsed
            FROM    warehouse_locations as wl
            LEFT JOIN
                    product_stock_warehouse as psw
            ON      psw.location = wl.location 
            WHERE   wl.unitId_unitId LIKE '1'
            GROUP BY wl.location 
        ) t1
GROUP BY substring(location, 1, 2)
ORDER BY substring(location, 1, 2)