How to group by 1 in SQL Server - sql-server

How can I group by 1 in SQL Server?
I have alot of SQL sum from Oracle need change to SQL Server. In sum column oracle they has been group by 1. But in Sql Server group by 1 false.
For example
Create table MyTable(
PRICE int
)
go;
select SUM(PRICE) as Total
from MyTable
Result return 1 row null.
In Oracle they have been group by 1 like this:
select SUM(PRICE) as Total
from MyTable
group by 1
Return no row.
How can I do it in Sql Server?

Group by 1 is not supported in SQL Server but you can put the same code like this:
select SUM(PRICE) as Total
from MyTable
having count(PRICE) > 0

In Sql Server <= 2012, As fa as i known . It not support GROUP by 1. But you can try sql like this will is the same.
--- Create 1 table example
CREATE TABLE table_name (
column1 int
);
--- Return 1 row if data is null:
select sum(column1) as total
from table_name
--- Return 0 row if data null <=> Oracle group by 1
select sum(column1) as total
from(
select column1, 1 as GroupBy from table_name
) a
group by GroupBy

The correct syntax for GROUP BY is
SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
Condition(WHERE) is optional.

Related

MS SQL: How to return a count(*) of 0 instead of empty when checking duplicated records

I create an SQL statement to check duplicated records in a table. If the table does not have duplicated records, the count should return zero. The actual result is the count return empty
SELECT COUNT(1) MY_ID_dup_count
FROM mytable
GROUP BY MY_ID
HAVING COUNT(1) >1
Expect Result:
MY_ID_dup_count
0
Actual Result:
MY_ID_dup_count
MS SQL version: Microsoft SQL Server 2017 - 14.0.3381.3 (X64)
The return is 1 record for every MY_ID group of 2 or more. You now want to count these if you want the count of MY_ID rather than the duplicate record count from all the groups. This counts both.
SELECT COUNT(*) as [GROUPS_COUNT], SUM(k.[MY_ID_COUNT]) as [RECORDS_COUNT]
FROM (
SELECT MY_ID, COUNT(*) as [MY_ID_COUNT]
FROM mytable
GROUP BY MY_ID
HAVING COUNT(*) > 1
) k
PS Wrap the SUM with ISNULL if you want 0 when there are no records to sum. (Can't remember if this is needed.)
Something like the following occurs to me:
Count the values ​​without 'having' and then count them with the condition you need
SELECT COUNT(v.MY_ID_dup_count)
FROM(
SELECT COUNT(1) MY_ID_dup_count
FROM mytable
GROUP BY MY_ID
--HAVING COUNT(1) >1
)V
where v.MY_ID_dup_count > 1
You are talking about post-processing the result of your duplicate-check. You could do it this way:
DROP TABLE IF EXISTS #Duplicates;
SELECT MY_ID_dup_count = COUNT(1)
INTO #Duplicates
FROM mytable
GROUP BY MY_ID
HAVING COUNT(1) > 1;
IF ##ROWCOUNT = 0
SELECT MY_ID_dup_count = 0;
ELSE
SELECT * FROM #Duplicates;

How to skip the max function which has only one entry when i do a group by in SQL Server

I have a requirement where I do a group by the table
Table
Name salary
------------
abc 10000
abc 1000
def 100
Query:
select max(salary)
from table
group by Name
Result:
abc 10000
def 100
I don't want 'def' to be displayed since it's a single entry in the table. How can I achieve this?
You can add a HAVING clause.
Having specifies a search condition for a group or an aggregate.
HAVING can be used only with the SELECT statement. HAVING is typically
used with a GROUP BY clause. When GROUP BY is not used, there is an
implicit single, aggregated group.
select
Name
,max(salary)
from table
group by Name having count(*) > 1
This will only return the aggregates for names that have more than 1 row, which seems to be what you want.
EXAMPLE
declare #table table (name varchar(16), salary int)
insert into #table
values
('abc',10000),
('abc',1000),
('def',100),
('xxf',100)
select
Name
,max(salary)
from #table
group by Name
having count(*) > 1

Check records from same table with unmatched values in multiple rows based on date

I want to select the unmatched combination from the same table:
Table 1
So as per the above table, #Id combination (#3,#4,#5) is missing for date 15-Sep-2018 and #Id combination (#8,#9,#10) is completely different for 15-Sep-2018 as compared to 14-Sep-2018.
So I want to select such IDs [ #Id combination (#8,#9,#10) ] and print it
How do I find this through query?
When you say "Combination #8" you actually just mean Server 3 + License 1? Something like this?
declare #daycount int
select #daycount = count(distinct [date]) from table1
select ServerID, LicenseID
from table1
group by ServerID, LicenseID
having count(*) != #daycount

Rows to Column conversion Sql query SQL SERVER

I have a table name #Table1(See the attachment) I want following out put (See the attachment)
#Raging Bull's answer is correct. Here is version using PIVOT
SELECT FormatType, [True], [False], [Blank], [True] + [False] + [Blank] AS Total
FROM
(
SELECT FormatType, Result
FROM Table1
) AS SourceTable
PIVOT
(
COUNT(Result)
FOR Result IN ([True], [False], [Blank])
) AS PivotTable
It produces the exact same result.
See result in SQL Fiddle
Try this:
SELECT FormatType,
ISNULL(COUNT(CASE WHEN Result='True' THEN '1' END),0) AS [True],
ISNULL(COUNT(CASE WHEN Result='False' THEN '1' END),0) AS [False],
ISNULL(COUNT(CASE WHEN Result='Blank' THEN '1' END),0) AS [Blank],
ISNULL(COUNT(1),0) AS [Total]
FROM Table1
GROUP BY FormatType
ORDER BY FormatType DESC
Explanation:
This query will select the FormatType along the count of each cases and the total. ISNULL is used for replacing NULL values with 0 (in case of FALSE in ASP).
Result:
FORMATTYPE TRUE FALSE BLANK TOTAL
PSP 1 2 1 4
ASP 1 0 2 3
See result in SQL Fiddle.

If any clause when grouping

Doing a Sum() on a column adds up the values in that column based on group by. But lets say I want to sum these values only if all the values are not null or not 0, then I need a clause which checks if any of the values is 0 before it does the sum. How can I implement such a clause?
I'm using sql server 2005.
Thanks,
Barry
Let's supose your table schema is:
myTable( id, colA, value)
Then, one approach is:
Select colA, sum(value)
from myTable
group by colA
having count( id ) = count( nullif( value, 0 ))
Notice that nullif is a MSSQL server function. YOu should adapt code to your rdbms brand.
Explanation:
count aggregate function only count not null values. Here a counting null values test.
You say that 0+2+3=0 for this case. Assuming that NULL+2+3 should also be zero:
SELECT GroupField,
SUM(Value) * MIN(CASE WHEN COALESCE(Value, 0) = 0 THEN 0 ELSE 1 END)
FROM SumNonZero
GROUP BY GroupField
The above statement gives this result
GroupField (No column name)
case1 5
case2 0
case3 0
with this test data
CREATE TABLE SumNonZero (
GroupField CHAR(5) NOT NULL,
Value INT
)
INSERT INTO SumNonZero(GroupField, Value)
SELECT 'case1', 2
UNION ALL SELECT 'case1', 3
UNION ALL SELECT 'case2', 0
UNION ALL SELECT 'case2', 2
UNION ALL SELECT 'case2', 3
UNION ALL SELECT 'case3', NULL
UNION ALL SELECT 'case3', 3
UNION ALL SELECT 'case3', 4
It makes no sense to eliminate 0 from a SUM because it wont impact the sum.
But you may want to SUM based on another field:
select FIELD, sum(
case when(OTHER_FIELD>0) then FIELD
else 0
end)
from TABLE
group by TABLE

Resources