SQL DISTINCT / GROUP BY无法正常工作

时间:2016-05-13 19:41:42

标签: sql syntax firebird

在这里忍受我,我对SQL很新。我写了以下查询,但DISTINCT基本上被我的WHERE语句否定了。这是因为表格中的日期后跟一个时间戳,因此如果订单项的时间有任何差异,它会生成一个新行。

在日期之后完全忽略所有内容的最佳方法是什么,以便不会因时间戳而生成新行?根据我的发现,我认为使用GROUP BY可以更好地实现这一点,但接缝始终会产生错误(很可能我不知道在何处放置聚合函数)。

非常感谢任何帮助。谢谢!

Select DISTINCT
 so.num AS Ref
,  so.shiptoname AS Recipient_Full_Name
, so.shiptoaddress AS Address_1
, so.shiptocity AS City
, stateconst.name AS State
, so.shiptozip AS Zip
, so.billtoname AS Buyer_Name
, qbclass.name AS Class
, soitem.datescheduledfulfillment AS Fulfillment_Date
From SO
JOIN stateconst
ON so.shiptostateid=stateconst.id
JOIN qbclass
ON so.qbclassid=qbclass.id
JOIN soitem
ON so.id=soitem.soid
WHERE DATESCHEDULEDFULFILLMENT LIKE '2016-05-10%'

2 个答案:

答案 0 :(得分:3)

使用CAST()datetime数据类型更改为date类型:

Select DISTINCT
 so.num AS Ref
,  so.shiptoname AS Recipient_Full_Name
, so.shiptoaddress AS Address_1
, so.shiptocity AS City
, stateconst.name AS State
, so.shiptozip AS Zip
, so.billtoname AS Buyer_Name
, qbclass.name AS Class
, CAST(soitem.datescheduledfulfillment as date) AS Fulfillment_Date
From SO
JOIN stateconst
ON so.shiptostateid=stateconst.id
JOIN qbclass
ON so.qbclassid=qbclass.id
JOIN soitem
ON so.id=soitem.soid
WHERE CAST(soitem.datescheduledfulfillment as date) = '2016-05-10'

答案 1 :(得分:0)

您确实需要查询输出中的日期吗?因为遗漏它会解决你的问题':

Select DISTINCT
 so.num AS Ref
,  so.shiptoname AS Recipient_Full_Name
, so.shiptoaddress AS Address_1
, so.shiptocity AS City
, stateconst.name AS State
, so.shiptozip AS Zip
, so.billtoname AS Buyer_Name
, qbclass.name AS Class

From SO
JOIN stateconst
ON so.shiptostateid=stateconst.id
JOIN qbclass
ON so.qbclassid=qbclass.id
JOIN soitem
ON so.id=soitem.soid
WHERE DATESCHEDULEDFULFILLMENT LIKE '2016-05-10%'