简体   繁体   中英

SQL Server Query group by clause

I have written Query. Below is that query

SELECT
  COUNT(amount) AS NR_Sales,
  DATEPART(YEAR, crn_dt) AS years
FROM c_Payment_service_fee
WHERE CFK_F_key IN (SELECT
  FK_2290F_key
FROM C_Submissions
WHERE FK_C_UP_key IN (SELECT
  PK_C_UP_key
FROM C_User_Profile
WHERE DATEPART(WEEK, crn_dt) BETWEEN 1 AND (DATEPART(WEEK, @date)))
AND DATEPART(WEEK, crn_dt) BETWEEN 1 AND (DATEPART(WEEK, @date)))
AND DATEPART(WEEK, crn_dt) BETWEEN 1 AND (DATEPART(WEEK, @date))
AND amount > 0
GROUP BY DATEPART(YEAR, crn_dt)

And one more

SELECT
  amount AS NR_Sales,
  DATEPART(YEAR, crn_dt) AS years
FROM c_Payment_service_fee
WHERE CFK_F_key IN (SELECT
  FK_2290F_key
FROM C_Submissions
WHERE FK_C_UP_key IN (SELECT
  PK_C_UP_key
FROM C_User_Profile
WHERE DATEPART(WEEK, crn_dt) BETWEEN 1 AND (DATEPART(WEEK, @date))
AND DATEPART(YEAR, crn_dt) = 2019)
AND DATEPART(YEAR, crn_dt) = 2019
AND DATEPART(WEEK, crn_dt) BETWEEN 1 AND (DATEPART(WEEK, @date)))
AND DATEPART(WEEK, crn_dt) BETWEEN 1 AND (DATEPART(WEEK, @date))
AND amount > 0
AND DATEPART(YEAR, crn_dt) = 2019

Both are working fine no error. But my problem is if i run first query 2019 count will be 303 and if run second query 269 data is displaying of 2019 year.

Where I making mistaking i am not able find the problem please help me with that.

SELECT
PK_C_UP_key
FROM C_User_Profile
WHERE DATEPART(WEEK, crn_dt) BETWEEN 1 AND 
(DATEPART(WEEK, @date))
AND DATEPART(YEAR, crn_dt) = 2019

is more restrictive than

SELECT
PK_C_UP_key
FROM C_User_Profile
WHERE DATEPART(WEEK, crn_dt) BETWEEN 1 AND 
(DATEPART(WEEK, @date))

So, the FK_C_UP_key could take more values from subquery in your first query.

SELECT COUNT(amount)AS NR_Sales,DATEPART(YEAR,crn_dt)AS years FROM c_Payment_service_fee GROUP BY DATEPART(YEAR,crn_dt)

You first query has:

SELECT COUNT(amount) AS NR_Sales, DATEPART(YEAR, crn_dt) AS years

Your second has:

SELECT amount AS NR_Sales, DATEPART(YEAR, crn_dt) AS years

Your are comparing the count of rows to the sum of a column. I'm not surprised they are different.

I don't know what you want, but I would recommend using this for both queries:

SELECT YEAR(crn_dt), COUNT(*) as num_rows,
       SUM(amount) as total_amount

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM