[英]Select entire row with more than one distinct column
我有一個基於發票項目的表格,我試圖在其中使用SQL來檢測物料/客戶組合的價格或貨幣在什么日期發生了變化。 該表包含一些客戶的發票,盡管材料可能很普通。
我的SQL技能非常基礎,我嘗試使用其他線程中使用的GROUP BY和DISTINCT嘗試了幾種不同的方法,但是我似乎總是會遇到麻煩。
數據基本上是這樣的:
Invoice Inv. Date Material Price Currency Per/Qty Customer
SE100 20140901 111111 1 EUR 1 840006
SE100 20140901 222222 2 EUR 1000 840006
SE100 20140901 333333 3 USD 1 840006
SE101 20140902 111111 1 EUR 1 840006
SE101 20140902 222222 2 EUR 1000 840006
SE101 20140902 333333 3 USD 1 840006
SE102 20140903 111111 2 EUR 1 840006
SE102 20140903 222222 2 USD 1000 840006
SE102 20140903 333333 3 USD 1 840006
SE103 20140904 111111 1 EUR 1 840006
SE103 20140904 222222 2 USD 1000 840006
SE103 20140904 333333 3 USD 1 840006
我要完成的工作基本上是為客戶/物料/貨幣/價格的所有不同組合按日期順序選擇第一行,然后為在選擇中多次出現的那些物料再選擇整個行(按物料分類)。價格或貨幣已從初始值更改。
使用上表中的數據從查詢中獲得的預期輸出將如下所示:
Invoice Inv. Date Material Price Currency Per/Qty Customer
SE100 20140901 111111 1 EUR 1 840006
SE102 20140903 111111 2 EUR 1 840006
SE103 20140904 111111 1 EUR 1 840006
SE100 20140901 222222 2 EUR 1000 840006
SE102 20140903 222222 2 USD 1000 840006
我希望我能以一種可以理解的方式解釋這個問題。 數據庫引擎是SQL Server 2005 Express。
任何幫助,將不勝感激...
SQL中的關鍵字DISTINCT
具有“唯一值”的含義。 當應用於查詢中的列時,它將從結果集中返回與該列具有唯一,不同值的行一樣多的行。 結果,它創建了一個分組的結果集,並且其他列的值是隨機的,除非由其他函數(例如,max,min,average等)定義。
如果要說要返回所有第06列具有特定值的行,則使用“ where Col 06 = value
”子句
SELECT mt.*
FROM (
SELECT DISTINCT col6
FROM mytable
) mto
JOIN mytable mt
ON mt.id =
(
SELECT TOP 1 id
FROM mytable mti
WHERE mti.col6 = mto.col6
-- ORDER BY
-- id
-- Uncomment the lines above if the order matters
)
我認為這是您想要的內容的直接翻譯:
select t.*
from mydata t join
(select Customer, Material, count(distinct price) as numprices
from mydata
group by Customer, Material
having count(distinct price) > 1
) cmcp
on t.customer = cmcp.customer and t.material = cmcp.material;
這省去了貨幣。 不幸的是,SQL Server不支持將多個參數用於distinct
。 您可以這樣包含它:
select t.*
from mydata t join
(select Customer, Material,
count(distinct cast(price as varchar(255)) + ':' + currency) as numprices
from mydata
group by Customer, Material
having count(distinct cast(price as varchar(255)) + ':' + currency) > 1
) cmcp
on t.customer = cmcp.customer and t.material = cmcp.material;
大多數數據庫都支持窗口/分析功能,因此您也可以將其表述為:
select t.*
from (select t.*,
min(cast(price as varchar(255)) + ':' + currency)) over (partition by Customer, Material) as minprice,
max(cast(price as varchar(255)) + ':' + currency)) over (partition by Customer, Material) as maxprice
from mydata t
) t
where minprice <> maxprice
order by Material, Inv_Date;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.