Truncate year, group by year and count another column in SQL - sql

I want to use the following sql code to get Year information from MyDate and count unique CustomerId but get error.
SELECT YEAR(MyDate) AS MyYear, COUNT(DISTINCT CustomerId) AS MyCustomerCount
FROM MyTable
GROUP BY MyYear
However the following code works.
SELECT YEAR(MyDate), COUNT(DISTINCT CustomerId)
FROM MyTable
GROUP BY YEAR(MyDate)
Why can't alias be used in this scenario?

Simply because this is how it was defined in SQL standard.
Syntax rules
Group by clause is defined as:
However Order by clause is defined as bellow
So here you can see alias exists after order by clause then we can use it normally but not after group by clause.

Related

using date of datetime in group by and order by in single SELECT versus using subquery

I (suddenly?) have trouble getting this very simple query to work on Google BigQuery without using a subquery and not sure why.
The data contains a datetime column and I just want to check up on the number of rows per day.
However, it keeps complaining I'm using the datetime column 'which is neither grouped or aggregated'.
SELECT date(datetime_col) as row_date, count(*) as count
FROM table1
GROUP BY date(datetime_col)
ORDER BY count DESC
Without the ORDER BY it works just fine. When I add the ORDER BY it suddenly complains the
'SELECT list expression references column 'datetime_col' which is
neither grouped nor aggregated'
If I remove the count and group by and order by on the date then it does work.
Now if I use a subquery to do the date casting in there it does work:
SELECT row_date, count(row_date) as count FROM
(SELECT date(datetime_col) as row_date FROM table1)
GROUP BY row_date
ORDER BY count DESC
So I'm wondering what is going on why the first single select query is not working and if that can be fixed without using the subquery?
Try putting row_date into GROUP BY:
SELECT date(datetime_col) as row_date, count(*) as count
FROM table1
GROUP BY row_date
ORDER BY count DESC

SAS SQL SELECT DISTINCT WITH GROUP BY

What if a SQL code as below?
Proc SQL;
SELECT DISTINCT ID,SUM(AMOUNT) AS M,SUM(NO) AS CNT
FROM CUSTOMER_LIST
GROUP BY ID
ORDER BY CNT DESC;
QUIT;
Use DISTINCT with GROUP BY. Any possible error will occur when using this combination Or DISTINCT just a redundant word?
Thanks~
Use DISTINCT with GROUP BY. Any possible error will occur when using this combination? Or DISTINCT just a redundant word?
This won't error, but that's just unnecessary redondancy. GROUP BY ID guarantees that each ID will appear only on one row in the resulset. There is no benefit for adding DISTINCT here - and it makes the intent of the query harder to understand.
On the other hand, there are situations where you would use DISTINCT without GROUP BY: typically when you want to deduplicate a set of columns, but do not need to use aggregate functions (SUM(), COUNT()...).
SELECT ID,SUM(AMOUNT) AS M,SUM(NO) AS CNT
FROM CUSTOMER_LIST
GROUP BY ID
ORDER BY CNT DESC;
We already group by id so no need distinct id

how to select two attributes at same time

I am new to sql, I would like to search account id and rule name in my table, but I got this error
Expression"AccountID must appear in the GROUP BY clause or be used in aggregate function".
I added it in count, it seems wrong, how to resolve this problem ?
This is the query:
SELECT AccountID, RuleName, COUNT(1) as COUNT
FROM(**)
WITH (***)
GROUP BY RuleName;
As the error said you need to add AccountID as well to group by
SELECT AccountID, RuleName, COUNT(1) as COUNT
FROM tbl
GROUP BY AccountID, RuleName;

Some two columns using alias in order by

I have this query:
select
id,
count(1) as "visits",
count(distinct visitor_id) as "visitors"
from my_table
where timestamp > '2016-01-14'
group by id
order by "visits", "visitors"
It works.
If I change to this
select
id,
count(1) as "visits",
count(distinct visitor_id) as "visitors"
from my_table
where timestamp > '2016-01-14'
group by id
order by (("visits") + ("visitors"))
I get
column "visits" does not exist
If I change to
select
id,
count(1) as "visits",
count(distinct visitor_id) as "visitors"
from my_table
where timestamp > '2016-01-14'
group by id
order by count(1) + count(distinct visitor_id)
it works again.
Why does it work for example 1 and 3, but not for example 2? Is there any way to order by the sum of two column using their aliases?
The alternatives I could think of:
Create an outer select and order it, but that would create extra code and I would like to avoid that
Recalculate the values in the order by statement. But that would make the query more complex and maybe I would lose performance due to recalculating stuff.
PS: This query is a toy-query. The real one is much more complicated. I would like to reuse the value calculated in the select statement in the order by, but all summed up together.
Expression evaluation order is not defined. If your visits + visitors expression is evaluated before aliases you will get the error shown here above.
Instead of using the alias try using the actual column also try change the type to varchar or nvarchar, and by that I mean the following:
select
id,
count(1) as "visits",
count(distinct visitor_id) as "visitors"
from my_table
where timestamp > '2016-01-14'
group by id
order by (CAST(count(1) AS VARCHAR) + CAST(count(distinct visitor_id) AS VARCHAR))

Summary Query to Sum Operations not working

SELECT price,total_price,SUM(mount) As TotalAmount
FROM sales
group by [date]
is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
You cannot select fields in the SELECT part which is not a part of an Aggregated function or specified in the the GROUP BY clause when using GROUP BY.
You can select "mount" because it's aggregated (SUM), but not price or total_price because they're not aggregated nor part of your group by date
You will need to either change your group by functionality, or the select part.
You have to group by the remaining tables that are not a function, therefore:
SELECT price,total_price,SUM(mount) As TotalAmount
FROM sales
Group by price,total_price
Order by date