我在查询中停留了几天,无法通过简单的查询对数据进行排序。
由于我的数据有点复杂,我以数据为例。
以下是数据表(原始数据)的摘录:
Products --- Qty --- Info
Chair --- 1 --- Sold
Lamp --- 1 --- Sold
Chair --- 3 --- Sold
Chair --- 1 --- Sold
Chair --- 2 --- Sold
Table --- 4 --- Sold
Computer --- 2 --- Sold
Chair --- 1 --- Returned
Table --- 1 --- Sold
Desk --- 3 --- Sold
Chair --- 2 --- Returned
Etc. (a lot of lines)
这是我求和的结果(仅是数量QTY
,取决于它是否已售出或是否在两个不同的列中返回)-ORDER BY:QtySold
,然后是{{1} },然后QtyRet
Prod
我想对它们进行排序:在此示例中,我想按Prod --- QtySold --- QtyRet --- Info
Chairs --- 95 ------ / ------ Sold
Tables --- 33 ------ / ------ Sold
Book --- 22 ------ / ------ Sold
Computer --- 22 ------ / ------ Sold
Lamp --- 19 ------ / ------ Sold
Desk --- 11 ------ / ------ Sold
Chairs --- / ------ 5 ------ Returned
Computer --- / ------ 2 ------ Returned
Tables --- / ------ 2 ------ Returned
进行排序,但是如果QtySold
出现两次,我希望第二个出现在第一个下面(例如椅子- 95-/-已售出,然后是椅子-/-5-返回,等等)
这是代码(它可能包含错误,因为我在这里直接写了它):
Prod
我想要获得的结果是:
SELECT
Prod=ttt.Prod,
QtySold=ttt.QtySold=CONVERT(Decimal(5,1),SUM(ISNULL(ttt.QtySold,0))),
QtyRet=CONVERT(Decimal(5,1),SUM(ISNULL(ttt.QtyRet,0))),
Info=ttt.Info
FROM(
SELECT
Prod=nte.Products,
QtySold=(CASE WHEN (ISNULL(nte.Info,'0')='Sold') THEN ISNULL(nte.Qty,0) ELSE 0 END),
QtyRet=(CASE WHEN (ISNULL(nte.Info,'0')='Sold') THEN 0 ELSE ISNULL(nte.Qty,0) END),
Info=nte.Info
FROM
nametableexemple nte
)ttt
GROUP BY ttt.Prod, ttt.Info
ORDER BY ttt.QtySold DESC, ttt.QtyRet DESC, ttt.Prod -- Here is the issue
(按DESC顺序订购Prod --- QtySold --- QtyRet --- Info
Chairs --- 95 ------ / ------ Sold
Chairs --- / ------ 5 ------ Returned --(because Chair is first with 95 Sold)
Tables --- 33 ------ / ------ Sold
Tables --- / ------ 2 ------ Returned --(because Table is 2nd with 33 Sold)
Book --- 22 ------ / ------ Sold
Computer --- 22 ------ / ------ Sold
Computer --- / ------ 2 ------ Returned --(because Computer is 4th w 22Sold)
Lamp --- 19 ------ / ------ Sold
Desk --- 11 ------ / ------ Sold
:95-33-22-22-19-19)
(但是第一项(主席)也是“返回的”信息,因此我需要使其直接显示在其下方)
是否可以以其他方式执行“排序依据”?我想避免创建UNION ALL,因为我的表包含太多列。
答案 0 :(得分:1)
尝试以下CTE-
WITH CTE
AS
(
SELECT Products,SUM(qty) Q,Info
FROM your_table
GROUP BY Products,Info
)
SELECT A.*
FROM CTE2 A
ORDER BY
(SELECT Q FROM CTE2 B WHERE B.Info = 'Sold' AND B.Products = A.Products) DESC,
1,
CASE WHEN info = 'Sold' THEN 1 ELSE 2 END
答案 1 :(得分:0)
创建CTE并将查询(不包含ORDER BY子句)括起来,然后进行条件排序:
with cte as (
<your query here>
)
select * from cte c
order by
case
when coalesce(c.QtySold, 0) <> 0 then c.QtySold
else (select QtySold from cte where prod = c.prod and coalesce(QtySold, 0) <> 0)
end desc,
QtySold DESC, prod
仅当coalesce()
产品行中的QtySold
为null
时,才需要功能'Returned'
。
如果是0
,请使用以下命令:
order by
case
when c.QtySold <> 0 then c.QtySold
else (select QtySold from cte where prod = c.prod and QtySold <> 0)
end desc,
QtySold DESC, prod