I have a query I wrote a while ago that returns a count. I would now like to see the rows that are being counted but I can't seem to get my query right. Here is the query that returns the count.
extern crate rustc_serialize;
use rustc_serialize::json::{Json, ToJson};
#[derive(Debug)]
enum ApiResult<T: Sized + ToJson> {
Ok(T),
Err(T),
}
trait ToApiResult<T: Sized + ToJson> {
fn to_api_result(&self) -> ApiResult<T>;
}
impl ToApiResult<Json> for Result<Option<String>, String> {
fn to_api_result(&self) -> ApiResult<Json> {
match *self {
Ok(Some(ref text)) => ApiResult::Ok(text.to_json()),
Ok(None) => ApiResult::Err(().to_json()),
Err(ref e) => ApiResult::Err(e.to_json()),
}
}
}
fn main(){
let r = Result::Ok(Some("hello".to_string()));
print!("{:?}", r.to_api_result());
}
and here is what I have come up with, but it returns duplicate shipment numbers
select count(distinct f_Shipmentnumber) from t_shipment shipment
join t_Pilot pilot on pilot.f_PilotID=shipment.f_Pilot_ID
where pilot.f_ProviderID='12' and shipment.f_ShipmentType=2
and shipment.f_date > DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)
Any help would be great. Thank!!
答案 0 :(得分:1)
根据你在评论中的答案,我假设当一个货物与一个货物相关联时,你不关心在结果中返回哪个飞行员。在这种情况下,您可以使用CTE和Row_Number()函数来解决此问题:
WITH cte AS (
select *
, ROW_NUMBER() OVER (PARTITION BY f_Shipmentnumber ORDER BY f_Shipmentnumber) AS rn
from t_shipment shipment
join t_Pilot pilot on pilot.f_PilotID=shipment.f_Pilot_ID
where pilot.f_ProviderID='12' and shipment.f_ShipmentType=2
and shipment.f_date > DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)
)
SELECT * FROM CTE WHERE rn=1
答案 1 :(得分:0)
You have to use group by, but in group by , you have to group by all columns and you have to decide which value you want to return on the other columns. some thing like this:
<!-- fake fields are a workaround for chrome autofill getting the wrong fields -->
<input style="display:none" type="text" name="fakeusernameremembered"/>
<input style="display:none" type="password" name="fakepasswordremembered"/>