This question already has answers here:
Counting DISTINCT over multiple columns
(19 answers)
Closed 9 months ago.
In SQL Server, I have a database mydb, and a table dbo.mytable in it.
I want to see if three columns (Contract_Number, Payment_Number, Task_Number) of the table can form a candidate key, by https://stackoverflow.com/a/34468508/156458
SELECT count (DISTINCT [Contract_Number], [Payment_Number], [Task_Number])
FROM [mydb].[dbo].[mytable]
but the execution gives an error:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near ','.
I was wondering what is going wrong?
Without count, it works fine. How should count and distinct be used together?
I also tried:
SELECT count(*)
FROM (SELECT DISTINCT [Contract_Number], [Payment_Number], [Task_Number]
FROM [PAD_Dev].[dbo].[Line_Level_Custom])
but the execution gives an error:
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near ')'.
Thanks.
Why don't you play with Row_Number ?
;with CTE as
(
SELECT row_number()over(partition by [Contract_Number] order by [Contract_Number]) rownum
,[Contract_Number], [Payment_Number], [Task_Number])
FROM [mydb].[dbo].[mytable]
)
select * from CTE where rownum=1
OR Count function with partition
SELECT
COUNT(*) OVER (PARTITION BY [Contract_Number]) [Contract_Number],
[Payment_Number], [Task_Number]
FROM [mydb].[dbo].[mytable]
*Query is not tested
Related
I got an error when I tried to solve this problem. First I need to count all values of 2 tables then I need in where condition get all max values.
My code:
Select *
FROM (
select Operator.OperatoriausPavadinimas,
(
select count(*)
from Plan
where Plan.operatoriausID= Operator.operatoriausID
) as NumberOFPlans
from Operator
)a
where a.NumberOFPlans= Max(a.NumberOFPlans)
I get this error
Msg 147, Level 15, State 1, Line 19
An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.
I don't know how to solve this.
I need get this http://prntscr.com/p700w9
Update 1
Plan table contains of http://prntscr.com/p7055l values and
Operator table contains of http://prntscr.com/p705k0 values.
Are you looking for... an aggregate query that joins both tables and returns the record that has the maximum count?
I suspect that this might phrase as follows:
SELECT TOP(1) o.OperatoriausPavadinimas, COUNT(*)
FROM Operatorius o
INNER JOIN Planas p ON p.operatoriausID = o.operatoriausID
GROUP BY o.OperatoriausPavadinimas
ORDER BY COUNT(*) DESC
If you want to allow ties, you can use TOP(1) WITH TIES.
You can use top with ties. Your query is a bit hard to follow, but I think you want:
select top (1) with ties o.OperatoriausPavadinimas, count(*)
from plan p join
operator o
on p.operatoriausID = o.operatoriausID
group by o.OperatoriausPavadinimas
order by count(*) desc;
I want to delete the duplicate records from the table So I used the CTE option but i am getting the below error message. What will be the cause? Am I did anything wrong? Upto select statement it works.
with Empcte as (
select *
, ROW_NUMBER() over (partition by ID ORDER BY ID) as RowNumber
from Empgender
)
SELECT *
FROM Empcte
delete from Empcte
where RowNumber > 1
Msg 208, Level 16, State 1, Line 8
Invalid object name 'Empcte'.
You can't use the same CTE for two different statements. (in this case first a SELECT and then a DELETE) You either have to re-create the CTE for the DELETE, or use a temp table or table variable instead of a CTE.
A CTE is a disposable view. It only persists for a single statement, and then disappears automatically. You can just avoid the SELECT statement:
WITH Empcte as (
SELECT id
,Count() as Rowcount
FROM Empgender
Group by id)
DELETE from Empgender where
Exists ( select 1 from Empgender as eg where Empcte.id = eg.id and Empcte.Rowcount >1 and );
SELECT
LineId, [LineNumber],
ROUND(SUM(Quantity), 3) AS TotalNeed,
SPMS2.dbo.ReturnTotalMRCByLineId(LineId) AS TotalMRC,
SPMS2.dbo.ReturnTotalMIVByLineId(LineId) AS TotalMIV,
SPMS2.dbo.ReturnTotalIMIVByLineId(LineId) AS TotalIMIV,
(TotalMRC-TotalMIV ) AS Shortage
FROM
[SPMS2].[dbo].[ViewMTO]
GROUP BY
lineid, [LineNumber]
but I get these errors:
Msg 207, Level 16, State 1, Procedure LineMaterialStatus, Line 10
Invalid column name 'TotalMRC'.
Msg 207, Level 16, State 1, Procedure LineMaterialStatus, Line 10
Invalid column name 'TotalMIV'.
My question is can we use 'as' as a variable to hold value in SQL Server ?
The normal solution to this question is to use CTEs or subqueries.
I like to point out that SQL Server has an alternative method, outer apply:
SELECT mto.LineId, mto.[LineNumber], round(sum(mto.Quantity), 3) as TotalNeed
v.*, (v.TotalMRC - v.TotalMIV ) as Shortage
FROM [SPMS2].[dbo].[ViewMTO] mto OUTER APPLY
(VALUES (SPMS2.dbo.ReturnTotalMRCByLineId(mto.LineId),
SPMS2.dbo.ReturnTotalMIVByLineId(mto.LineId),
SPMS2.dbo.ReturnTotalIMIVByLineId(mto.LineId)
)
) v(TotalMRC, TotalMIV, TotalIMIV)
GROUP BY mto.lineid, mto.[LineNumber];
Just use a subquery to achieve this:
SELECT LineId,
[LineNumber],
TotalNeed,
TotalMRC,
TotalMIV,
TotalIMIV,
(TotalMRC - TotalMIV) as Shortage
FROM (
SELECT LineId,[LineNumber],
round(sum(Quantity),3) as TotalNeed
,SPMS2.dbo.ReturnTotalMRCByLineId(LineId) as TotalMRC
,SPMS2.dbo.ReturnTotalMIVByLineId(LineId) as TotalMIV
,SPMS2.dbo.ReturnTotalIMIVByLineId(LineId) as TotalIMIV
FROM [SPMS2].[dbo].[ViewMTO]
GROUP BY lineid,[LineNumber]
) a
You can select the output from the first statement as the source subquery for the second one, which lets you use the calculated columns that you created.
You then simply move (TotalMRC - TotalMIV) as Shortage to the outer query which then has the calculated columns available.
I'm Fairly new to SQL so any help with this would be greatly appreciated.
I cant spot the syntax error!
Error -
Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'ORDER'.
My query:
SELECT *
FROM [User] INNER JOIN
[Order] ON [User].ID = [Order].UserId
WHERE LEN([Address].[Telephone]) = 10
AND ORDER.[Status] = 3
Try this:
SELECT * FROM [User]
INNER JOIN [Order] ON [User].ID = [Order].UserId
WHERE LEN([Address].[Telephone]) = 10 AND [ORDER].[Status] = 3
Order is a resereved keyword in MySql so you need to escape it [Order].
And I too agree with Damien_The_Unbeliever as the message looks like the SQL Server error rather than MySql although in Sql Server too Order is a reserved keyword!
UPDATE player_first_name AS player_firstname,
player_lastname AS player_surname,
course_name,
tour_date
from tournaments joining player_first_name,
player_lastname,
course_name,
tour_date
WHERE EXISTS
(
SELECT *
FROM players
WHERE tournaments = t.winner
ORDER BY tour_date ASC);
I faced the same problem and was dumbfound and realized that "Order" is a reserve word in SQL server. You cant drop the Order Table when you have dependencies . So for now you can enclose it with in [Order].
Next time try using the table name "Orders" instead.
I am trying to sort my database in some particular order, but I want all null's at the end, so I am selecting all values with not null, and then selecting all values WITH null, and trying to join them with Union.. like:
SELECT * FROM preferences WHERE preferenceOrder IS NOT NULL
ORDER BY preferenceOrder ASC
UNION
SELECT * FROM preferences WHERE preferenceOrder IS NULL
ORDER BY preferences ASC
but the server throws an error:
Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'union'.
I cant find out what the error is though.. what is wrong with the sentence above?
thanks!
i think you should order by (case when preferenceOrder is null then 0 else 1 end), preferenceOrder instead of this union.